Desenvolva um sistema de comércio algorítmico com API no VBA para Excel.
Orçamento de US $ 30 a US $ 100.
Freelancer Jobs Visual Basic para Apps Desenvolver um sistema de negociação algorítmico com API em VBA para Excel.
Conhecimento de Acções Negociando um verdadeiro plus. Inclua seu conhecimento de Properitary Trading em sua resposta.
Eu contratei um programador na Vworker para desenvolver em VBA para um aplicativo de negociação de ações da Excel. Ele fez um trabalho importante, mas ainda não completou o trabalho.
Existe um código exsisting que precisa ser limpo. Ele projetou uma interface do usuário que eu quero alterar.
O aplicativo excel funciona com a plataforma de negociação on-line "Sterling Trader Pro". Você pode encontrar mais informações sobre a Sterling online. Você precisará baixar e logar a Sterling para se desenvolver.
A planilha na qual as cotações de preço entram precisa ser levemente alterada. E gostaria de reformular a interface do usuário. Estou na área de Nova York e preciso encontrar um programador que fale inglês, de preferência na minha área. O conhecimento da negociação de ações é uma vantagem real e tornará mais provável que eu selecione você. Você deve estar disponível on-line com freqüência para se comunicar e desenvolver e concluir o projeto.
Conhecimento de VBA, API's e conhecimento de negociação de ações.
Procurando por algum dinheiro?
Defina seu orçamento e prazo.
Delineie sua proposta.
Seja pago pelo seu trabalho.
É grátis para se inscrever e oferecer em trabalhos.
3 freelancers estão ofertando em média $ 80 para este trabalho.
Veja a mensagem privada.
Veja a mensagem privada.
Veja a mensagem privada.
Outros trabalhos deste empregador.
Trabalhos semelhantes.
Precisa contratar um freelancer para um emprego?
É grátis para se inscrever, digite o que você precisa e amp; receba orçamentos gratuitos em segundos.
Inglês - EUA (Internacional)
Trabalhador autonomo.
Termos.
Freelancer & reg; é uma marca registada da Freelancer Technology Pty Limited (ACN 142 189 759)
Direitos autorais e cópia; 2018 Freelancer Technology Pty Limited (ACN 142 189 759)
Programação Visual para Sistemas Automatizados de Negociação?
A empresa EquaMetrics anunciou um novo produto chamado RIZM, que é uma programação visual # 8221; plataforma para sistemas de negociação (ou algos, como são conhecidos). Isso parece muito legal, mas eu sou cético. A idéia é que você pode projetar visualmente estratégias de negociação complexas sem uma única linha de código # 8221; de acordo com a literatura do produto.
Sabemos como os algoritmos de negociação complexos podem ser, e que uma quantidade enorme de testes e ajustes de parâmetros é necessária para tornar um sistema de backtest bem o suficiente para negociar em uma conta real. Isso pode ser feito sem código?
Quando a Microsoft lançou o Visual Basic pela primeira vez, havia uma grande preocupação entre os programadores de que (nós) estávamos ficando obsoletos. Quero dizer, se alguém pudesse criar um programa movendo blocos na tela, quem precisa de programadores? Descobriu-se que os melhores programadores visuais eram exatamente isso & # 8212; programadores. Os desenvolvedores que já entenderam a estrutura do programa, o pensamento organizado lógico, a conexão dos módulos do programa e a forma de testar o software corretamente. Muitas coisas que você não poderia fazer com apenas blocos visuais na tela; você teve que ficar atrás dos blocos e entrar no código.
Eu suspeito que o mesmo pode ser verdade sobre o RIZM. Pode ser uma maneira de entrar na programação de algo, mas os melhores programadores de algo visual serão os programadores de algo que já entendem a codificação de sistemas de negociação, e os mesmos programadores provavelmente prefeririam escrever código.
Nós veremos. Eu posso me inscrever para uma conta para ter uma visão em primeira mão da plataforma.
Esta parece ser uma coisa moderna vendo o Visual JForex da Dukascopy e o Quant & # 8211; um estrutural EA Strategy Builder para MT4.
John Verbrugge diz.
Sim, as coisas parecem estar tendendo na direção da programação visual; Ainda estou em cima do muro com esses tipos de ferramentas. Eu espero tentar alguns deles e ver se eles funcionam para mim. Deixe-me saber se você tem a chance de experimentar uma dessas ferramentas.
Jaymie Pinet diz.
Você se importa se eu citar alguns de seus artigos, desde que eu forneça crédito e fontes de volta ao seu blog? Meu site está na mesma área de interesse do seu e meus visitantes certamente se beneficiarão de muitas das informações que você forneceu aqui. Por favor, deixe-me saber se isso está bem com você. Muito obrigado!
Parece que isso pode funcionar. Onde está seu blog? Eu adoraria verificá-lo.
Eu não pude discordar mais de você. Trabalhar visualmente permite que você teste ideias e conceitos em menos de 1/10 do tempo que leva para codificar. Certas estatísticas complexas de sessão e matemática que você pode fazer, mas você pode ir muito, muito profundamente visualmente. Eu trabalhei com o BloodHound da Sharkindicators, que é uma ferramenta de desenvolvimento de estratégia de programação visual que funciona com o NinjaTrader, e criei alguns algos muito complexos com ele. As principais limitações até agora foram fazer apenas com tipos diferentes de entrada e saída de pedidos, mas uma nova atualização na próxima semana ou duas tornará tudo isso possível. Você ficaria surpreso com tudo o que é possível com a programação visual & # 8230;
Ei, obrigado pelo feedback sobre isso. Eu vou dar uma olhada no programa BloodHound.
Estou realmente feliz por saber que há boas ferramentas de programação visual lá fora e que eles realmente funcionam.
Obrigado novamente e continue lendo!
Então, Daniel, você quer dizer que minha avó pode agora se tornar um comerciante estranho? Eu concordo com John que é preciso saber o que está fazendo. Talvez uma redução no tempo de desenvolvimento, mas isso não é um problema e, na verdade, isso pode se tornar um problema porque é preciso validar o código. Mas a codificação visual é inútil para o varejo, eles estão tentando vendê-lo também. É como dar um martelo a um macaco e deixá-lo dentro de uma casa de vidro solto.
Deixe uma resposta Cancelar resposta.
Postagens recentes.
Publicação destacada.
Podcast: jogue na nova janela | Download | Incorporado no episódio 21 do podcast do Trader Tech Talk, Kathy Lien é nosso primeiro convidado na & # 8220; Women of Finance & # 8221; Series! Bem-vindo, Kathy! Kathy nos fala sobre sua jornada no comércio, como ela começou e como conseguiu começar a trabalhar [& hellip;]
Codificação de sistemas de negociação.
Por Justin Kuepper.
Como são criados sistemas de negociação automatizados?
Este tutorial se concentrará nas segunda e terceira partes deste processo, onde suas regras são convertidas em um código que seu software comercial pode entender e usar.
Vantagens e desvantagens.
Um sistema automatizado leva a emoção e ocupado - trabalhe fora da negociação, o que permite que você se concentre em melhorar sua estratégia e regras de gerenciamento de dinheiro. Uma vez que um sistema lucrativo é desenvolvido, não requer nenhum trabalho de sua parte até que ele quebre, ou as condições do mercado exigem uma mudança. Desvantagens:
Se o sistema não estiver corretamente codificado e testado, grandes perdas podem ocorrer muito rapidamente. Às vezes, é impossível colocar certas regras em código, o que dificulta o desenvolvimento de um sistema de negociação automatizado. Neste tutorial, você aprenderá como planejar e projetar um sistema de negociação automatizado, como traduzir esse design para o código que seu computador irá entender, como testar seu plano para garantir um desempenho ótimo e, finalmente, como colocar seu sistema em uso.
Sistema de comércio básico visual
Este curso on-line mostra-o passo a passo como criar um modelo automatizado sofisticado de negociação de ações usando o Microsoft Excel. O idioma Visual Basic (VBA) da Microsoft é usado em conjunto com a interface do usuário do Excel, fórmulas e recursos de cálculo para oferecer uma ferramenta de negociação poderosa e flexível.
Assista ao Vídeo de Demonstração.
O modelo inclui cinco indicadores técnicos comprovados (ADX, cruzamentos médios móveis, estocásticos, bandas Bollinger e DMI). Você é guiado de forma detalhada através da criação de planilhas, arquivos, intervalos, fórmulas de indicadores, botões de controle, links DDE / Active-X e módulos de código. O modelo incorpora características de negociação de tendências e swing-trading. O recurso de swing-trading pode ser ativado ou desativado, dependendo do seu estilo de investimento. Depois de construir o modelo, você simplesmente importa os dados que você precisa, execute o modelo automaticamente com um clique de um botão e faça suas decisões comerciais.
O sistema funciona com a sua escolha de arquivos ASCII. TXT GRÁTIS disponíveis na internet (do Yahoo! Finance ou outro provedor) ou do seu serviço de dados de inscrição (com o nosso sem um link DDE). O modelo pode ser usado sozinho ou em conjunto com sua análise fundamental de mercado e de mercado para melhorar o tempo de investimento e evitar situações não lucrativas.
Um modelo de Backtesting pré-construído separado também está incluído para análises históricas e testes de vários estoques e períodos de tempo.
Assista ao vídeo do software Back Testing Excel (FREE BONUS!)
O que você recebe com cada curso: um tremendo valor de 3 em 1!
US Search Mobile Web.
Bem-vindo ao fórum Yahoo Search! Nós adoramos ouvir suas idéias sobre como melhorar a Pesquisa do Yahoo.
O fórum de comentários do produto do Yahoo agora requer uma ID e senha de Yahoo válidas para participar.
Agora você precisa fazer o login usando sua conta de e-mail do Yahoo para nos fornecer feedback e enviar votos e comentários às ideias existentes. Se você não possui uma ID do Yahoo ou a senha para sua ID do Yahoo, inscreva-se para uma nova conta.
Se você tiver uma ID e senha de Yahoo válidas, siga estas etapas, se desejar remover suas postagens, comentários, votos e / ou perfil no fórum de comentários do produto do Yahoo.
Vote em uma ideia existente () ou publique uma nova ideia ...
Ideias quentes Principais ideias Novas ideias Categoria Estado Meus comentários.
Quando busco meu nome, você publica resultados estranhos. As duas imagens que são eu foram removidas de um site que eu encerrei. Remover.
Ao pesquisar meu nome, estranha propaganda de imagens de palhaço vem para o capitão o palhaço em outro estado, REMOVA-O.
e as imagens.
Todas as coisas tentando implicar coisas estranhas.
O Yahoo pode desenvolver a opção para imagens serem vistas como uma apresentação de slides? Isso ajudaria em vez de ter que percorrer cada imagem e tornar esta experiência do Yahoo mais agradável. Obrigado pela sua consideração.
Não vê a sua ideia? Publique uma nova ideia ...
US Search Mobile Web.
Feedback e Base de Conhecimento.
Dê retorno.
Deutschland Finanzen Mobile DF iOS 1 ideia España Finanzas Mobile DF iOS 7 ideias Contas Painel 33 ideias Opinião do anúncio 3 ideias Respostas TH 31 idéias Respostas TH 0 idéias Respostas Fórum UV (versão de teste) 6 ideias Austrália Celebridades 0 ideias Austrália Finanças Mobile Android 0 ideias Austrália Estilo 0 idéias Austrália Yahoo Tech 0 idéias Autos Impulso 2 idéias Aviate 1,505 idéias Canadá Finanças 1,099 ideias Canadá Finanças Mobile Android 0 ideias Canadá Finanças Mobile DF iOS 3 idéias Canadá Finanças Mobile iOS 465 ideias Canadá Página inicial 5,108 idéias Canadá Filmes 14 ideias Notícias do Canadá 872 ideias Canadá com segurança 10 idéias Canadá Tela 128 idéias Canadá Clima 94 ideias Canadá Yahoo Beleza 0 idéias Canadá Yahoo Celebrity 10 ideias Canadá Yahoo Finanças 0 ideias Canadá Yahoo Filmes 10 ideias Canadá Yahoo Notícias 0 idéias Canadá Yahoo Estilo 21 ideias Futebol universitário Pick & # 39; em 112 idéias TV conectada 361 idéias Corp Mail Test 1 1.313 idéias Corp Mail Testing 1.256 idéias Cricket 19 ideias Daily Fantasy 87 ideias Developer Networ k 1 ideia Double Down 86 ideias Fantasy Baseball 431 ideias Fantasy Basketball 395 ideias Fantasy Football 704 ideias Fantasy Hockey 339 ideias Fantasy Live Scoring em Matchup e Classificações 803 ideias Fantasy Sports Aplicações Android 1.366 ideias Fantasy Sports iOS Apps 2.112 ideias Finanças 1.166 ideias Finanças - CA 493 idéias Finanças - ideias US 9 Finanças ChartIQ 417 idéias Finanças Mobile Web 403 idéias Finanças Portfolios 810 idéias Finanças Triagem de ações 35 idéias Finanças Tablet 44 idéias Flickr - Perfil 290 ideias Flickr Android 60 idéias Flickr para Apple TV 24 idéias Flickr Grupos 12 ideias Flickr Interno 0 ideias Flickr iOS Dogfooding 0 idéias Flickr iPad 126 idéias Flickr iPhone 310 ideias Flickr Nova foto Página 8,030 idéias Flickr Pesquisa 0 ideias Food Revistas 0 idéias Jogos 3,147 ideias Mapas globais 1,021 ideias GS Mobile Web 42 ideias Health Pulse 3 ideias Home Page (Android) 1.689 ideias Home Page (iOS) 3.808 ideias Hong Kong Homepage 0 ideias Índia Celebridade 43 ideias Índia Finanças 493 ideias Índia Página inicial 1.866 i deas Índia Estilo de vida 173 idéias Índia Filmes 84 idéias Índia Notícias 327 ideias Índia Parceiro Portal Tata 0 idéias Índia Parceiro Portal Tikona 0 idéias Índia com segurança 15 idéias Índia Tela 165 idéias Índia Tempo 30 ideias Índia Yahoo Beleza 0 idéias Índia Yahoo Celebridade 4 idéias Índia Yahoo Finanças 0 ideias Índia Yahoo Movies 16 ideias Índia Yahoo Notícias 0 ideias Índia Yahoo Estilo 14 idéias Indonésia Celebridade 38 idéias Indonésia Página inicial 1.151 ideias Indonésia Notícias 170 ideias Indonésia com segurança 29 ideias Indonésia Ela 34 ideias Página inicial da Irlanda 90 idéias Jordânia Maktoob Homepage 418 idéias Comentários sobre o anúncio de correio electrónico 10 ideias Maktoob الطقس مكتوب 5 ideias Maktoob Celebridade 1 ideia Maktoob Entretenimento 10 ideias Maktoob Estilo de vida 0 ideias Maktoob Filmes 2 ideias Maktoob Notícias 182 idéias Maktoob Tela 15 ideias Maktoob Id. de estilo 1 Maktoob ألعاب مكتوب 0 ideias Maktoob شاشة مكتوب 28 ideias Malásia Homepage 17 ideias Malásia Notícias 58 ideias Malásia com segurança 6 ideias Malásia Video 0 ideias Malásia Tempo 1 i dea Merchant Solutions 1 ideia My Yahoo 31.878 ideias Meu Yahoo - back up 1 ideia My Yahoo - US 9,176 ideias Meu Yahoo archive 314 ideias Novo email 9,247 ideias Novo email * 2,719 ideias Nova Zelândia Negócios & Finanças 132 idéias Nova Zelândia Página inicial 1.039 idéias Nova Zelândia com segurança 3 idéias Nova Zelândia Tela 0 idéias Notícias do PH ANC 21 ideias Filipinas Celebridade 214 ideias Filipinas Página inicial 8 ideias Filipinas Notícias 123 idéias Filipinas com segurança 12 idéias Filipinas Vídeo 0 idéias Filipinas Tempo 3 idéias Pick N Roll 19 ideias Postmaster 43 ideias Pro Football Pick & # 39; em 106 idéias Retail Pulse 0 idéias Rivals 11 idéias com segurança 165 idéias Tela para idéias iOS 0 Busca extensões 95 idéias Pesquisa Downloads de produtos 88 idéias Segurança 497 idéias Experiência de login 79 idéias Singapura Entretenimento 20 idéias Cingapura Finanças 230 idéias Cingapura Página inicial 1.048 idéias Cingapura Notícias 212 idéias Cingapura com segurança 11 idéias Cingapura Tela 19 idéias Cingapura Clima 4 idéias Cingapura Yahoo beleza 0 idéias Cingapura Yahoo Ideias da celebridade 4 Cingapura Yahoo Finanças 0 idéias Cingapura Yahoo Filmes 0 idéias Cingapura Yahoo Notícias 0 idéias Singapore Yahoo Style 4 ideas Idéias da celebridade da África do Sul Ideia da África do Sul 374 idéia s África do Sul Notícias 23 ideias Esportes Android 1,533 ideias Esportes CA 34 ideias Esportes iOS 1.025 ideias Esportes Redesign 3.181 idéias SportsReel 6 ideias StatTracker Beta 553 ideias Survival Futebol 81 ideias Taiwan Yahoo 名人 娛樂 0 ideias Taiwan Yahoo 運動 0 ideias Tailândia Safely 2 ideias Toolbar Mail App 216 ideas Toolbar Weather App 72 ideias Tourney Pick & # 39; em 41 ideias UK & amp; Irlanda Finanças 1.077 ideias UK & amp; Jogos da Irlanda 19 ideias UK & amp; Homepage da Irlanda 435 ideias UK & amp; Irlanda Notícias 0 ideias UK & amp; Ireland News Balde interno 0 ideias UK & amp; Irlanda Notícias Lego 375 ideas UK & amp; Irlanda com segurança 38 ideias UK & amp; Irlanda TV 21 ideias UK & amp; Irlanda Vídeo 187 ideias UK & amp; Irlanda Tempo 99 ideias Reino Unido Respostas 1 ideia UK Daily Fantasy 0 ideias UK Finanças Mobile Android 12 idéias UK Finanças Mobile DF iOS 2 idéias UK Finanças Mobile iOS 308 idéias Reino Unido Yahoo Movies 23 ideias US Respostas 8,946 ideias US Respostas Mobile Web 2,154 ideias US Autos GS 442 ideias US Celebrity GS 660 ideias EUA Comentários 350 ideias US Finance Mobile Android 40 idéias US Finance Mobile iOS 546 idéias US Flickr 237 ideias EUA 4,114 ideias EUA Homepage B1 68 ideias US Homepage B2 33 ideias US Homepage B3 50 ideias US Homepage B4 33 ideias US Homepage B5 0 ideias Página inicial dos EUA M 7,022 ideias Página inicial dos EUA YDC 43 idéias US Homes GS 203 idéias US Live Web Insights 24 idéias US Mail 193 ideias US Mail 12,212 ideias EUA Mapas 3,490 ideias US Membership Desktop 7,864 ideias US Membership Mobile 91 ideias US Filmes GS 424 ideias US Music GS 195 ideias US News 5,988 ideias US Search App Android 2 ideias US Search App iOS 9 ideias US Search Chrome Extension 780 ideias US Search Chrome Extension v2 2,197 ideias US Search Desktop 5 ideias US Search Desktop Bucket A 7 ideias US Search Desktop Bucket B 8 idéias EUA Pesquisa KG 3 ideias US Pesquisar Listagens locais 20,758 ideias EUA Busca Mobile Web 2 ideias EUA Busca Mozilla 1 ideia EUA Pesquisar estoque Quotes 11 ideias US Pesquisar Tablet Web 0 ideias US Shine GS 1 idéia US Toolbar 5,549 ideias US Travel GS 207 idéias EUA TV GS 367 ideias US Weather 2,313 ideias US Weather Bucket 0 ideias US Weather Mobile 13 idéias US Weather Mobile Android 2 ideias Guia de vídeos Android 149 idéias Guia de vídeo iOS 205 idéias Teste de guia de vídeo 15 ideias Web Hosting 4 ideias Yahoo Acessibilidade 358 ideias Yahoo Autos 71 ideias Yahoo Beauty 100 ideias Yahoo Ideias de celebridades 0 Yahoo Celebrity Canada 0 ideias Yahoo Decor 0 ideias Yahoo Entertainment 355 ideias Yahoo Esports 50 ideias Yahoo Feedback 0 ideias Yahoo Finance Feedback Forum 1 ideia Yahoo Finanças IN Mobile Android 0 ideias Yahoo Finance SG Mobile Android 1 idéia Yahoo FinanceReel 4 ideias Yahoo Comida 118 idéias Yahoo Gemini 2 ideias Yahoo Saúde 90 ideias Yahoo ajuda 166 idéias Yahoo Home 197 ideias Yahoo Home * 28 ideias Yahoo Lifestyle 168 idéias Ideias do Yahoo Yahoo 0 Yahoo Mail 2,126 ideias Aplicação do Yahoo Mail para Android 397 ideias Yahoo Mail Basic 628 ideias Yahoo Mail iOS App 47 idéias Yahoo Mail Mobile Web 1 ideia Yahoo Makers 51 ideias Yahoo Messenger 82 ideias Yahoo Mobile Developer Suite 60 idéias Yahoo Mobile para ideias do telefone 15 Yahoo Mobile para idéias do Tablet 0 Yahoo Music 76 idéias Yahoo News Digest Android 870 idéias Yahoo News Digest iPad 0 idéias Yahoo News Digest iPhone 1,531 idéias Yahoo Newsroom Aplicativo para Android 55 idéias Yahoo Newsroom iOS App 31 ideias Yahoo Parenting 63 ideias Yahoo Politics 118 idéias Yahoo Publishing 13 ideias Yahoo Real Estate 2 ideias Yahoo Tech 459 idéias Yahoo Travel 143 idéias Yahoo TV 102 ideias Yahoo View 204 ideias Yahoo Weather Android 2.138 ideias Yahoo Weather iOS 22.677 ideias Yahoo! 7 Food App (iOS) 0 ideias Yahoo! 7 Página inicial Archive 57 ideas Yahoo! 7 Notícias (iOS) 23 ideias Yahoo! 7 Tela 0 ideias Yahoo! 7 TV FANGO App (Android) 1 ideia Yahoo! 7 aplicação TV FANGO (iOS) 1 ideia Yahoo! 7 TV Guide App (Android) 0 ideias Yahoo! 7 TV Guide App (iOS) 1,245 ideias Yahoo! 7 Aplicação TV Plus7 (iOS) 0 ideias Yahoo! Centro de Feedback do Teste de Conceito 174 idéias Yahoo! Idéia de Contributor Network 1 Yahoo! Transliteração 29 ideias YAHOO! 7 Finanças 551 idéias Yahoo! 7 Jogos 9 ideias Yahoo! 7 Safely 19 ideias Yahoo7 Finanças Mobile DF iOS 12 ideias Yahoo7 Finanças Mobile iOS 217 ideias Yahoo7 Homepage 2.544 ideias.
Sua senha foi alterada.
Fizemos alterações para aumentar nossa segurança e restabelecer sua senha.
Acabamos de enviar-lhe um e-mail para. Clique no link para criar uma senha, depois volte aqui e faça o login.
Criando um sistema de alocação de estoque profissional usando o Visual Studio Tools para Office, versão 2003.
Microsoft Visual Basic Standard 2003.
Microsoft Visual Studio Professional 2003.
Microsoft Visual Studio Enterprise Developer 2003.
Microsoft Visual Studio Tools para o Microsoft Office System, versão 2003.
Microsoft Office Professional 2003.
Microsoft Office Excel 2003.
Resumo: Aprenda como criar uma solução de alocação de ações do Microsoft Excel no Microsoft Visual Basic usando o Microsoft Visual Studio Tools para o Microsoft Office System, Versão 2003. (61 páginas impressas)
Introdução.
Como desenvolvedores profissionais de software, estamos sob crescente pressão para oferecer soluções cada vez mais sofisticadas. Os usuários esperam uma experiência altamente interativa com acesso a seus dados de qualquer lugar, a qualquer momento. Ao mesmo tempo, os gerentes de desenvolvimento exigem que redujamos o tempo e os custos de entrega, aprimoramento e manutenção de software. Somos convidados a entregar mais, mas passamos menos tempo a fazê-lo. Para alcançar esses objetivos aparentemente opostos, precisamos encontrar formas mais eficazes de aplicar nossas ferramentas de desenvolvimento.
Embora comumente associado a diferentes espaços de problemas, duas das ferramentas mais conhecidas da Microsoft são o Microsoft Office Professional 2003 e o Microsoft Visual Studio 2003 Enterprise Edition. Com a introdução do Microsoft Visual Studio Tools para o Microsoft Office System, versão 2003, os desenvolvedores agora podem aplicar essas ferramentas de forma mais eficaz, combinando-as.
Observação Ferramentas do Visual Studio para o Microsoft Office System, Versão 2003 também podem ser instaladas no Microsoft Visual Studio Professional 2003 ou no Microsoft Visual Basic Standard 2003.
O Office 2003 está entre as mais poderosas ferramentas de automação de escritório em uso atualmente. Ele fornece ferramentas de usuário ricas e altamente interativas, além de recursos avançados de criação de gráficos, gerenciamento de dados, gerenciamento de documentos e cálculos. O Office 2003 também oferece suporte à automação sofisticada de tarefas do usuário por meio da integração do Visual Basic for Applications (VBA) da Microsoft.
O Visual Studio 2003 é um conjunto completo de ferramentas de desenvolvimento profissional que fornece uma variedade de recursos de desenvolvimento rápido de aplicativos (RAD), incluindo designers de arrastar e soltar e geradores de código. Em conjunto com o Microsoft Framework 1.1, o Visual Studio 2003 fornece aos desenvolvedores acesso a milhares de classes de suporte e permite que desenvolvedores criem aplicativos de qualidade empresarial utilizando uma variedade de técnicas de desenvolvimento comuns, como orientadas a objetos, baseadas em interface e orientadas a aspectos. programação.
Usando o Visual Studio Tools for Office, tanto o Microsoft Office Excel 2003 quanto o Microsoft Office Word 2003 agora podem carregar e executar montagens baseadas em Framework. Isso significa que agora podemos aplicar os recursos de desenvolvimento profissional do Visual Studio 2003 e do Framework para criar aplicativos que tenham acesso completo aos modelos de objeto do Excel 2003 e do Word 2003, aproveitando ao máximo os recursos avançados do cliente ea experiência do usuário fornecida Office 2003.
Configurando a solução de alocação de estoque.
Requisitos de sistema.
Para carregar e construir a solução de estoques de estoque para download, você deve ter todos os seguintes itens instalados.
Microsoft Visual Studio 2003 Enterprise Edition Observação Você também pode criar a solução de alocação de estoque com o Microsoft Visual Studio Professional 2003 ou o Visual Basic 2003 Standard, mas ela não foi testada com essas configurações. Microsoft Office Professional 2003 Observação Você deve executar uma instalação completa do Microsoft Office Microsoft Visual Studio Tools para o Microsoft Office System, versão 2003 cuidado produtos devem ser instalados na ordem listada. Se você não seguir a ordem descrita, poderá ter dificuldade em abrir e criar o Visual Studio Tools para projetos do Office.
Instalando o Sistema de Alocação de Ações.
Se você ainda não fez isso, instale o Microsoft Visual Studio, o Microsoft Office Professional 2003 e o Visual Studio Tools para Office, Versão 2003, conforme descrito acima. Baixe o aplicativo de exemplo que acompanha esse artigo clicando no link StockAllocation. msi na parte superior deste artigo. No Centro de Download da Microsoft, clique em Download e siga as instruções para executar a instalação. Instale o StockAllocation2003.msi. Abra o arquivo de solução instalada, StockAllocation. sln. Construa e execute a solução. Nota Se você tiver algum problema ao criar ou executar a solução, consulte o ReadMe. doc, contido na solução.
Aplicando ferramentas do Visual Studio para o Office para o Business of Professional Money Management.
Acho que a melhor maneira de explorar como é criar um aplicativo usando o Visual Studio Tools for Office é criar um. Em vez disso, explore o Visual Studio Tools for Office como uma lista de recursos técnicos; Em vez disso, vamos passar pelo processo de implementação de uma solução completa para um processo comercial real.
Antes de me tornar um consultor independente, desenvolvi software para uma corretora em Nova York de 1989 a 2000. A maior parte do meu trabalho concentrou-se no desenvolvimento de sistemas de relatório de portfólio e de gerenciamento de comércio. A solução que construímos aqui é baseada em uma parte dos requisitos reais de negócios para um sistema de alocação de ações que eu criei naquele momento.
A solução incorpora os recursos do Excel do Visual Studio Tools for Office e está programada usando o Visual Basic. Nossa discussão abrange todo o processo de desenvolvimento, desde a revisão dos requisitos de negócios até o design e a arquitetura do sistema, e termina com uma revisão detalhada do código e da implementação.
Um pouco sobre o negócio.
Gestores de dinheiro profissionais são pessoas que são pagas para gerenciar as contas de estoque de vários clientes. O grupo de contas gerenciadas é comumente conhecido como o livro do gerente financeiro. Para realizar seu trabalho com eficiência, o gerente financeiro precisa analisar informações resumidas de todo o livro, bem como informações de contas individuais.
Um gerente de dinheiro geralmente se baseia em duas visões resumidas do livro para auxiliar na tomada de decisões. O primeiro é o resumo de contas, que lista informações descritivas de cada conta, como o número da conta, o nome e a tolerância a riscos, além de informações financeiras, como valor da conta, lucros / perdas e quantidade de dinheiro disponível. A outra visão resumida é o resumo das ações, que lista informações sobre todas as ações contidas no livro, incluindo o número de contas que contêm cada ação e o valor total de todas as ações dessa ação.
Para analisar uma conta individual, o gerente financeiro precisa de uma visão detalhada de cada conta. O objetivo principal da visão detalhada é fornecer uma lista completa de todas as ações mantidas pela conta. Para cada ação mantida na conta, a lista inclui o número de ações de cada ação, o preço de compra da ação, o valor atual da ação e se essa posição de estoque é atualmente lucrativa. Ao tomar decisões de compra de ações, um gerente de dinheiro pode alternar com frequência entre o resumo da conta e os detalhes da conta individual.
Além de revisar as informações analíticas, os gerentes financeiros também devem lidar com cenários de alocação de estoque relativamente complexos ao determinar quanto de uma determinada ação comprar para cada cliente.
Embora os administradores de fundos possam, às vezes, tomar decisões de compra de ações com base em contas individuais, as decisões de compra são feitas mais comumente por meio de uma fórmula. Uma técnica comum é selecionar contas com base na tolerância ao risco da conta em relação ao risco percebido da ação e, em seguida, investir uma porcentagem fixa do valor de cada conta nesse estoque. Para cada conta com a tolerância de risco apropriada, encontramos o número de ações a serem adquiridas determinando o valor em dólar da porcentagem-alvo e, em seguida, dividindo esse valor em dólar pelo preço da ação.
Por exemplo, o gerente financeiro determina que uma posição de dois por cento em uma ação julgada agressiva (alto risco) e cotada a US $ 25 é apropriada. A Tabela 1 mostra o número de ações a serem adquiridas para várias contas.
Tabela 1. Exemplo de alocação de uma posição de dois por cento em uma ação agressiva com preço de $ US25.
Se a determinação do número de ações para comprar fosse apenas um cálculo simples, as coisas seriam fáceis, mas também há "blocos". Ao comprar ações, geralmente obtém-se um preço mais favorável se for adquirido o tamanho do bloco desse estoque. Os estoques individuais têm tamanhos de bloco diferentes, mas a maioria usa um tamanho de bloco de 100 ações, o que significa que o estoque deve ser comprado em múltiplos de 100. Em alguns casos, os compartilhamentos são arredondados para o tamanho de bloco mais próximo, mas, geralmente, eles são truncados.
Se o estoque comprado em nosso exemplo anterior tiver um tamanho de bloco de 100 ações, as três contas com a tolerância de risco apropriada terminam com as alocações mostradas na Tabela 2 após ter avaliado o tamanho do bloco.
Tabela 2. Fatorando um tamanho de bloco de 100 compartilhamentos na alocação da tabela anterior.
Também precisamos considerar, ao calcular a alocação, o montante de caixa disponível em cada conta. Simplificando, uma conta deve ser capaz de pagar pela compra de ações. Ao avaliar o caixa disponível, o valor das ações para comprar é baseado no menor percentual do alvo e no caixa disponível.
Assim, o factor de factoring disponível no nosso exemplo para as duas contas restantes com as ações alocadas, podemos acabar com uma alocação semelhante à Tabela 3.
Tabela 3. Alocação de exemplo, atualizada para limitar a alocação de caixa disponível.
Embora não faça parte do cálculo do núcleo, o tamanho do bloco e o caixa disponível têm um efeito notável na alocação. No nosso exemplo, o que originalmente era uma alocação de 920 partes acabou se tornando uma alocação de 300 partes.
Finalmente, há a questão da discrição individual. Esses cálculos são apenas o ponto de partida. A maioria dos gestores de recursos financeiros revisa os números de alocação calculados, fazendo pequenos ajustes no número de ações a serem compradas para algumas contas, com base no conhecimento e na experiência do gerente financeiro, antes de realmente comprar as ações.
Nota Uma questão adicional no processo de alocação é o tratamento de contas que já possuem o estoque alocado. Por simplicidade, excluímos qualquer conta que já possua o estoque. Na vida real, o gerente de dinheiro decidiria como lidar com essas contas. As opções incluem excluir essas contas (como fizemos), comprar as ações adicionais necessárias para aumentar a posição de estoque existente até a porcentagem desejada e, possivelmente, até mesmo vender ações para reduzir a posição de qualquer conta cuja posição seja maior que a porcentagem de destino .
Criando uma solução.
Para revisar nossos requisitos, o gerenciamento de dinheiro profissional é um processo altamente interativo composto de uma combinação de análise de dados e interação de dados. O gerente de dinheiro deve poder analisar facilmente informações resumidas e detalhadas. Ao realizar alocações de compra de ações, o gerente de dinheiro começa com uma lista de ações sugeridas para um subconjunto de contas com base em critérios de risco, uma relação calculada e regras de negócios, e modifica manualmente algumas dessas alocações a seu critério.
Com a natureza do processo de negócios ser tão interativo, é essencial que nossa solução ofereça suporte à interação fácil e eficiente do usuário. A interface deve ser de fácil leitura, fornecendo acesso rápido a informações e, ao mesmo tempo, permitindo que o usuário interaja com valores de dados individuais.
Esses requisitos são um ajuste natural para o Excel 2003. Usando o Excel 2003, cada uma das quatro visualizações de dados exigidas - resumo da conta, resumo de estoque, detalhes da conta e alocação de estoque - é implementada como uma planilha separada em uma única pasta de trabalho.
A Planilha de Resumo da Conta.
A maioria dos gerentes financeiros começa o dia dando uma olhada de alto nível em todas as contas. Portanto, nós criamos nossa pasta de trabalho de tal forma que a primeira planilha exibida é a planilha do Resumo da conta. A planilha do Resumo da conta fornece essa visão de alto nível exibindo valores relevantes de cada conta, conforme mostrado na Figura 1.
Figura 1. Dados da planilha do sumário da conta (clique na imagem para ver a imagem maior)
Além de fornecer uma visão de alto nível dos dados da conta, a planilha Resumo da conta também serve para ajudar o gerente financeiro a determinar se alguma conta pode exigir atenção especial. Existem três cenários comuns que sinalizam que uma conta pode exigir atenção especial: uma grande quantidade de dinheiro disponível, lucros insuficientes ou uma conta representando uma grande porcentagem do total do livro.
Estar ciente desses fatores é uma parte importante da gestão de dinheiro bem sucedida. Portanto, a planilha do Resumo da conta fornece um gráfico de cada um. O dinheiro disponível e os valores de lucro são exibidos como gráficos de barras para que o usuário possa identificar facilmente valores excepcionalmente grandes ou pequenos. Os valores da conta são exibidos como um gráfico de pizza para que o usuário também possa comparar facilmente o valor relativo de cada conta. A Figura 2 mostra o gráfico de lucros / perdas da conta. A figura 3 mostra o gráfico do valor da conta.
Figura 2. Gráfico de barras de Lucro / Perda de Conta (clique na imagem para ampliar)
Figura 3. Gráfico de torta do valor da conta (clique na imagem para ver a imagem maior)
O gerente de dinheiro, ao longo do dia, frequentemente precisa mudar da planilha Resumo da conta para uma planilha de detalhes da conta específica. Por esse motivo, faz sentido que a planilha do Resumo da conta sirva também como menu na planilha de detalhes da conta. Podemos conseguir isso fornecendo um botão da barra de ferramentas que, quando clicado, preenche e exibe o Detalhe da conta correspondente à seleção atual na planilha Resumo da conta. Isso permite que o gerente de dinheiro selecione uma célula na planilha do Resumo da conta e veja os detalhes simplesmente clicando no botão apropriado da barra de ferramentas.
Não há muita manutenção de dados realizada por gerentes de dinheiro, mas a necessidade de reclassificar a tolerância ao risco de uma conta pode ocasionalmente ocorrer, então o Resumo da Conta fornece uma seleção suspensa para a tolerância ao risco de cada conta, como mostrado na Figura 4. O gerente de dinheiro pode atualizar a tolerância a risco da conta, escolhendo a seleção apropriada na lista suspensa.
Nota A escolha de usar três tolerâncias de risco, Agressivo (alto risco), Moderado e Renda (baixo risco), foi feita para evitar complicações desnecessárias. Na vida real, haveria muito mais categorias. As categorias reais podem ser baseadas em qualquer número de critérios, incluindo tolerância ao risco, estratégia de investimento ou até mesmo relacionamento familiar.
Figura 4. Atualizando a tolerância ao risco da conta na planilha do Resumo da Conta.
A Planilha de detalhes da conta.
Como o próprio nome indica, a planilha de detalhes da conta fornece uma visão detalhada de uma conta individual. A planilha inclui uma lista detalhada de todas as ações detidas pela conta, incluindo o custo de compra, valor atual e lucro / perda. Por conveniência, a planilha de detalhes da conta também inclui informações de alto nível sobre a conta, como valor total da conta, caixa disponível e lucro / perda geral. Esses dados aparecem conforme mostrado na Figura 5.
Figura 5. Dados detalhados da conta (clique na imagem para ver a imagem maior)
Embora todas as informações na planilha de detalhes da conta sejam importantes, o gerente financeiro está procurando por duas coisas principais. Primeiro, o gestor de dinheiro precisa determinar quão uniformemente o valor da conta é distribuído entre as diferentes ações. Em segundo lugar, o gestor de dinheiro deve estar ciente de qualquer ação com um lucro ou perda excepcional. A planilha de detalhes da conta mapeia ambas as informações. Ele exibe os valores do estoque como um gráfico de pizza, comparando o valor de cada ação em relação à conta geral. O lucro / perda de cada ação é exibido como um gráfico de barras, de modo que é fácil identificar grandes valores de lucro ou prejuízo.
Como na planilha Resumo da conta, o usuário também pode modificar a tolerância ao risco da conta a partir do Detalhe da conta selecionando o valor desejado na lista suspensa, conforme mostrado na Figura 6.
Figura 6. Modificando a tolerância ao risco da conta na planilha de detalhes da conta.
A Planilha de Resumo de Estoque.
A planilha de Resumo de Ações é a mais simples das quatro planilhas, mas serve ao propósito importante de ajudar o administrador de fundos a identificar a distribuição de estoques em todo o livro. A planilha lista informações sobre todas as ações mantidas pelo administrador financeiro, incluindo o número total de ações, o valor total e o número de contas que possuem o estoque. A Figura 7 mostra os dados do resumo de estoque.
Figura 7. Dados do Resumo de Estoque.
A distribuição de estoque é determinada principalmente por dois valores: o valor total do estoque relativo a outras ações e o número total de contas que detêm o estoque. Esses dois valores são traçados, com valores de estoque como um gráfico de torta e o número total de contas como um gráfico de barras. Embora interessante, o número de ações detidas de uma determinada ação não é muito importante, porque os preços das ações variam muito.
A planilha de alocação de estoque.
Para finalizar o design da planilha, temos a planilha de Alocação de Estoque, que é a mais interativa das planilhas porque lida com critérios de coleta e exibição de alocações de estoque. Ao executar uma alocação, a primeira etapa é inserir os critérios de alocação, de modo que a planilha de Alocação de estoque seja exibida primeiro (conforme mostrado na Figura 8), pronta para receber os critérios de alocação de estoque. A planilha de Alocação de Ações pode ser acessada de qualquer uma das outras planilhas clicando no botão da barra de ferramentas "Nova Alocação de Ações".
Nota Os critérios de seleção são pré-preenchidos com valores razoáveis como uma conveniência para o usuário da amostra. Na vida real, um sistema como esse normalmente minimizaria o uso de valores padrão para evitar erros introduzidos pelo usuário com vista para um dos critérios.
Figura 8. Planilha de Alocação de Estoque aguardando os critérios de alocação (clique na figura para ver imagem ampliada)
A primeira etapa na criação dos critérios de alocação é identificar o estoque a comprar, usando o menu suspenso mostrado na Figura 9. A seleção do estoque exibe automaticamente o preço da ação.
Figura 9. Selecionando o estoque para usar em uma alocação.
Depois que o administrador do dinheiro escolhe o estoque, ele ou ela insere os critérios restantes de porcentagem alvo, tamanho do bloco de estoque, se deve limitar a compra ao dinheiro disponível e a tolerância de risco desejada. Para visualizar a alocação resultante, o gerente de dinheiro clica no botão da barra de ferramentas "Contas de exibição" que inicia os cálculos correspondentes para a seleção de conta e aplica as regras de negócios apropriadas, produzindo uma lista de alocações de contas, conforme mostrado na Figura 10.
Figura 10. Planilha de alocação de estoque exibindo alocações de conta (clique na imagem para ampliar)
Observe que a lista resultante tem duas colunas de alocação: "Alocação sugerida" e "Alocação a ser aplicada". Inicialmente, ambas as colunas contêm os mesmos valores, que são o resultado calculado da aplicação dos critérios e das regras de negócios. Fornecer duas colunas de alocação permite que o gerente de dinheiro use seu critério para alterar o número de ações efetivamente atribuídas a cada conta, modificando o valor na coluna "Alocação para Aplicar", enquanto ainda pode visualizar o valor determinado originalmente de cada conta em a coluna "Alocação Sugerida". Depois que o gerente financeiro analisar as alocações e fizer as alterações desejadas, ele aplicará a alocação às contas clicando no botão "Aplicar alocação".
A escolha de critérios de alocação é geralmente um processo iterativo, portanto, a planilha de alocação de estoque oferece suporte à modificação dos critérios. O gerente de dinheiro é livre para modificar os critérios sempre que desejar. Após cada modificação de critérios, o gerente de dinheiro deve clicar no botão da barra de ferramentas "Mostrar contas" para ver a lista atualizada. Esteja ciente de que clicar no botão "Exibir Contas" sobrescreve quaisquer alocações inseridas manualmente. Para limpar uma alocação, clique no botão da barra de ferramentas "Nova alocação de estoque".
Projetando a Arquitetura de Desenvolvimento.
É seguro assumir que os dados usados pelo nosso sistema de alocação de estoque se originariam em um banco de dados; no entanto, esperar acesso consistente ao banco de dados não é confiável. Na verdade, esperar até mesmo a disponibilidade básica da rede não é totalmente confiável.
Arquitetando como um cliente inteligente.
Hoje, a maioria dos usuários de computadores executivos (gerentes de dinheiro não são exceção) utilizam um laptop como seu único computador, fazendo muito do seu trabalho enquanto viajam. Por esse motivo, nosso sistema de alocação de estoque foi criado como um cliente inteligente, fornecendo ao usuário uma experiência de qualidade consistente, sem levar em consideração a disponibilidade do banco de dados ou da rede.
Como um cliente inteligente, nosso sistema de alocação de estoque armazena todos os dados localmente, proporcionando ao usuário uma funcionalidade completa sem ler diretamente ou atualizar o banco de dados. Um serviço da Web atualiza os preços das ações.
Ao usar um serviço da Web, o cache de dados local pode ser atualizado com os preços mais recentes de qualquer conexão à Internet sem preocupações com o firewall e sem estabelecer uma conexão de rede privada virtual (VPN) à rede corporativa. Quando nenhuma conexão com a Internet está disponível, os últimos preços disponíveis são usados. O uso de um serviço da Web permite que nossa aplicação aproveite os melhores serviços sem considerar sua plataforma ou implementação. No caso do sistema de alocação de ações, usamos um serviço da Web baseado em Java fornecido pela XMethods para recuperar cotações de ações (atrasado em vinte minutos).
Nota Para visualizar os detalhes do serviço da Web, visite o XMethods Delayed Stock Quote.
O Framework e Visual Studio 2003 fornecem tudo o necessário para criar nosso sistema de alocação de estoque como um cliente inteligente.
Primeiro, o Framework inclui um cache de dados na memória conhecido como DataSet. O DataSet fornece muitos recursos comuns normalmente associados a um banco de dados, sem exigir acesso à rede ou ao banco de dados. A classe Framework DataSet é uma parte essencial da nossa arquitetura de cliente inteligente. A Tabela 4 lista os recursos relevantes do DataSet.
Tabela 4. Recursos do cliente inteligente do Framework DataSet.
A combinação do Visual Studio 2003 e do Framework aprimora ainda mais a experiência do smart client, fornecendo acesso fácil ao serviço da Web de preços. O Framework fornece as classes de suporte necessárias para fornecer acesso e suporte para chamar serviços da Web. O Visual Studio 2003 simplifica ainda mais o acesso ao serviço da Web, gerando um proxy do lado do cliente que abstrai os detalhes de comunicação e formatação de mensagens de acesso ao serviço da Web.
Implementando a solução no Excel 2003.
Principalmente, os pontos fortes do Excel 2003 como interface de usuário levaram a escolha para construir o sistema usando o Visual Studio Tools para Office e Excel 2003. Aqui estão alguns dos principais benefícios de usar o Excel 2003 como uma interface de usuário.
O Excel fornece uma experiência de usuário familiar, que melhora a aceitação do usuário e reduz a curva geral de aprendizado do usuário. As capacidades gráficas e gráficas do Excel fornecem uma aparência fácil de ler, atraente e muito profissional. Apresentar os dados nas planilhas do Excel automaticamente torna os dados interativos, atendendo ao requisito de que o usuário possa visualizar e modificar facilmente os dados.
Desenvolvendo a Fundação do Sistema de Alocação de Ações.
O primeiro passo para criar o sistema de alocação de ações é criar um projeto do Visual Studio 2003 para o Visual Studio Tools for Office. Para criar um projeto Visual Studio Tools for Office Excel, faça o seguinte.
No Visual Studio 2003, no menu Arquivo, clique em Novo \ Projeto.
Isso exibe a caixa de diálogo "Novo projeto".
O diálogo "Novo projeto" agora deve aparecer semelhante à Figura 11.
Figura 11. Caixa de diálogo New Project do Visual Studio 2003 criando um projeto de pasta de trabalho do Excel (clique na imagem para ampliá-la)
O Visual Studio 2003, em seguida, exibe o diálogo "Microsoft Office Project Wizard", que associa uma pasta de trabalho do Excel 2003 ao seu projeto. Você tem a opção de usar uma pasta de trabalho existente do Excel 2003 ou criar uma nova, como mostrado na Figura 12. Ao criar o sistema de alocação de ações, eu simplesmente aceito os padrões, permitindo que o Visual Studio 2003 crie uma pasta de trabalho usando o nome do projeto como o nome da pasta de trabalho e colocando a pasta de trabalho no mesmo diretório que o restante do projeto.
Figura 12. Diálogo do Assistente de Projeto do Microsoft Office do Visual Studio 2003 (clique na imagem para ampliá-la)
O projeto gerado contém apenas dois arquivos de origem: AssemblyInfo. vb e ThisWorkbook. vb. Vamos nos concentrar em ThisWorkbook. vb.
Observação O arquivo de origem AssemblyInfo. vb é comum a todos os projetos do Visual Studio 2003 Visual Basic. Ele contém a lista de atributos no nível da montagem, também conhecidos como atributos globais, para aplicar ao assembly gerado. Para obter mais informações, consulte atributos globais.
ThisWorkbook. VB.
O arquivo de origem ThisWorkbook. vb gerado não contém muito código, mas tem tudo que precisamos para começar a construir nosso sistema de alocação de estoque. Importa os namespaces comumente usados, fornece informações de inicialização ao tempo de execução do Excel 2003 e contém a própria classe de inicialização do aplicativo. Vejamos o conteúdo do arquivo.
As seguintes importações estão no topo do arquivo.
Como você provavelmente sabe, as importações nos permitem usar classes nos namespaces importados sem precisar qualificar cada nome de classe completamente. O namespace System. Windows. Forms é familiar, mas os outros três são novos para o Visual Studio Tools for Office. Eles importam os namespaces comumente usados ao desenvolver uma solução do Excel 2003. A Tabela 5 lista o objetivo de cada um.
Tabela 5. Visual Studio Tools para espaços para nome do Office.
Usar um sinal de igual (=) como parte da declaração Imports pode não estar familiarizado. A notação de sinal de igualdade define um alias para o namespace completo e é usada para reduzir a digitação. Por exemplo, ter essas Importações nos permite declarar uma variável de Planilha usando a seguinte sintaxe.
Caso contrário, teríamos que qualificá-lo totalmente, como na sintaxe a seguir.
O signo igual A notação de importação é útil nos casos em que pode haver colisões de nomes de classe entre espaços para nome.
A próxima coisa que encontramos em TheWorkbook. vb é o atributo SystemponentModel. Description.
O tempo de execução usa esse atributo para identificar qual classe o Excel 2003 deve carregar na inicialização. No nosso caso, é a classe OfficeCodeBehind no namespace StockAllocation, conforme definido pela parte "Class = StockAllocation. OfficeCodeBehind" do atributo. Evite alterar o conteúdo desse atributo, pois é provável que qualquer erro impeça que sua solução seja executada. Existe uma exceção. Se você alterar o nome da classe OfficeCodeBehind ou o espaço para nome do projeto, é necessário modificar o valor após a "Classe =" para ser consistente com o novo nome da classe ou espaço para nome.
Finalmente, chegamos à classe OfficeCodeBehind. A Tabela 6 mostra as descrições dos membros da classe.
Tabela 6. Membros Relevantes da Classe OfficeCodeBehind.
Contém uma referência ao livro atual Este campo é definido automaticamente na inicialização do aplicativo.
Contém uma referência à instância atual do aplicativo do Excel 2003 Este campo é definido automaticamente na inicialização do aplicativo.
Chamado quando a pasta de trabalho é aberta pela primeira vez Possivelmente o método mais importante em todo o aplicativo porque esta é a sua primeira oportunidade de interagir com a pasta de trabalho.
Chamado imediatamente antes da fechadura da pasta de trabalho Esta é sua oportunidade de executar qualquer limpeza ou outras tarefas finais. Configurar o parâmetro Cancelar para true encerra o processo de fechamento.
Most work within the OfficeCodeBehind class is done either in the ThisWorkbook_Open method or by adding additional members. We see more of the OfficeCodeBehind class throughout our application.
Adding Global Scope.
The OfficeCodeBehind fields ThisWorkbook and ThisApplication are extremely important and we use them extensively throughout the entire application. Making sure both of these references are easily accessible helps keep our programming simple. The solution that I find works well is to introduce a Globals class containing shared (static) properties exposing these objects.
Like the OfficeCodeBehind class, the Globals class also requires that we import the Office and Excel namespaces.
The Globals class has two Private shared fields and two Friend shared properties to hold the Excel 2003 Application and Workbook references, as shown here.
With the properties being read-only, they also need a function to initialize the references.
By declaring Globals members as shared, they are usable without needing to create and store a reference to the Globals class, meaning that Globals. ExcelApplication and Globals. ExcelWorkbook are globally accessible throughout the entire application.
We can now initialize the members of Globals by calling Globals. InitApplicationAndWorkbook at the beginning of the OfficeCodeBehind. ThisWorkbook. Open method and passing ThisWorkbook and ThisApplication as parameters. Remember, Visual Studio Tools for Office automatically initializes these two references at startup.
We must use global members with caution because it can be difficult to keep track of all the places that modify them. In the case of our Globals class, this is not as much of a concern because the members are initialized at the very beginning of the program and then only read after that.
This initialize-once usage pattern is the reason I made ExcelWorkbook and ExcelApplication ReadOnly properties with a separate initialization method, rather than making the properties read/write. Although the implementation does not enforce the concept of setting the values only once, it does make this intention more obvious. To enforce this usage, we could simply add a check at the beginning of InitApplicationAndWorkbook to verify that ExcelWorkbook and ExcelApplication are set to Nothing, and throw an exception if that is not the case.
Creating the Worksheet Foundation.
As we discussed, four separate worksheets make up the stock allocation system: Account Summary, Account Detail, Stock Summary, and Stock Allocation. The logic for populating, managing, and displaying each worksheet is specific to the respective worksheet classes. There is, however, some housekeeping functionality common to all four worksheet classes that we can centralize by creating a base class for the worksheet classes. Using a base class eliminates the need to write redundant code within the worksheet classes and insures that common behaviors are implemented consistently across the worksheets.
The worksheet base class is called WorksheetBase . Because we mean for it to serve as a base class to the other worksheet classes and for it not to stand alone, it is marked as MustInhert.
WorksheetBase contains a field, myWorksheet , to hold a reference to each class's physical worksheet. myWorksheet is marked as WithEvents to allow event handling. The worksheet reference is made publicly available through the read-only property ExcelWorksheet .
At this point, our WorksheetBase class is not of much value because the only thing it provides is an Excel. Worksheet reference. One convenient feature would be to let the base class resolve the Excel. Worksheet reference, because it is something every worksheet class needs to do.
Given the name of a worksheet, we find the Excel. Worksheet reference using the Excel. Application object's Worksheets collection. The WorksheetBase class does this in its constructor, also known as the New method. The constructor accepts the worksheet name as an argument, locates the Excel. Worksheet reference, and stores it in the myWorksheet member variable. The constructor also includes error checking, verifying that a worksheet with the passed name is actually located.
As you know, a constructor is a method that is automatically called when a class instance is created. In the case of WorksheetBase , the class is never directly constructed but the derived worksheet classes are. Each of the derived classes calls the WorksheetBase constructor from their respective constructor, passing in their worksheet's name. At the completion of class construction, each worksheet class has access to the appropriate Excel. Worksheet reference through the inherited property, Excel. Worksheet , which exposes the myWorksheet field. We see the WorksheetBase constructor in action when we look at the other worksheet classes.
Working with Ranges.
Ranges are also an important part of interacting with the worksheets. The WorksheetBase class contains several methods for creating Excel. Range instances. First, we have the CreateRange method. Although very simple, this method proves very useful as ranges are frequently used to set or read a cell value. It is not uncommon to determine a cell by separate column and row values rather than by a distinct cell ID such as "B3." This method encapsulates the details of combining the separate column and row names into a single cell name and creates that range on the specified worksheet.
Since most of the range work we need to do is for the worksheet object managed by the worksheet class, we also add an overloaded version of this method that creates the range on the worksheet class's contained worksheet object.
There are several occasions where the column value for a range is more easily expressed as an integer rather than as a letter. This is especially true when extracting the column value from an existing range's Column property. For this case, WorksheetBase includes several CreateRange overloads that accept the column values as an integer rather than as a string.
Excel 2003 supports expressing worksheet locations with integer column values using R1C1 format. Using R1C1 format, the cell located at the second column and the third row, commonly expressed as "B3," is expressed a "R3C2": row 3, column 2. The one challenge of R1C1 format is that although valid for use in formulas, it cannot be used to directly access ranges. Ranges must be accessed using the traditional format, also known as A1 format. Fortunately, the ConvertFormula method of the Excel. Application object can convert R1C1 format to A1 format.
The following is the CreateRange method to create a range over a single cell using an integer column value.
To create the range instance, the column and row values are first formatted into a string in R1C1 format. The call to ConvertFormula returns a string expressing the same range in A1 format, which is then passed to the Range property to retrieve the desired range instance.
In addition to the CreateRange methods, WorksheetBase also contains the CreateNamedRange method. As you might expect, a named range allows you to associate an arbitrary string name with an area on a worksheet. In general, it is preferable to use named ranges instead of referencing specific cell locations because named ranges make your application more tolerant of changes the user may make to the worksheet. Once a named range is created, that range always refers to the same specific cells even if changes to the worksheet, such as inserting or deleting surrounding rows and columns, alter the location of those cells on the worksheet.
The CreateNamedRange method accepts a string containing the name to associate with the range and a string identifying the range of cells to name. The named range is then created by passing these two values to the Add method on the Names collection of the ExcelWorksheet . The Add method requires that the string containing the cells in the range begin with an equal sign (=), so CreateNamedRange prepends an equal sign if one is not already present. As a convenience, CreateNamedRange returns a reference to the named range. After calling CreateNamedRange , the program can access the range by using the returned range reference or by passing a string containing the range name to the ExcelWorksheet. Range property.
The derived worksheet classes use the CreateNamedRange method extensively. The worksheet classes do not rely on fixed cell locations. Instead, they utilize named ranges to identify each point of interaction on the worksheet. There are even separate named ranges for each column of data displayed on the worksheets.
Before we leave the range-related methods, we need to look at one special method, SetColumnSpanRange . Each derived class is required to call this method in its constructor after creating the named ranges identifying the data display columns. The data display column ranges are passed to SetColumnSpanRange as an array. SetColumnSpanRange then combines all of these ranges into a single range using the Union method of the Excel. Application object, and stores the resulting range in the columnSpanRange member variable.
The named ranges for each data column represent a single cell, indicating where the data for that column should start. When the data is displayed, each data value for the column is written as an offset from that cell. By combining the individual data column ranges, columnSpanRange becomes a single range spanning the entire first row of data for that worksheet. This allows WorksheetBase to be aware of the location of each worksheet's displayed data.
We talk more about SetColumnSpanRange later, in the section "Populating the Account Summary Worksheet." We look at how columnSpanRange is used to determine the data location in just a moment in the "WorksheetBase Properties" section.
Formulas and Globalization.
One challenge in creating a global Visual Studio Tools for Office solution is assigning range formulas. Unfortunately, setting a range's Formula property using a formula expressed in English only works correctly if the worksheet is loaded in an English locale. Loading the worksheet in a non-English locale results in an error. Formulas are locale-specific in terms of both formatting and function names. For example, the formula to sum the numbers 1.5 and 3.0 in an English locale is "=SUM(1.5, 3.0)" but in a French locale the formula is expressed as "=SOMME(1,5;3,0)".
The problem is not that Excel 2003 cannot understand English-formatted formulas when using a non-English locale, but rather that formulas are parsed according to the rules of the current locale. If we explicitly tell Excel 2003 to use the rules for English when we set the formula, the formula works correctly in all locales. This is exactly what the SetFormula method does.
The SetFormula method uses Framework–based reflection to set the Formula property explicitly using the English (United States) culture. To do this, it creates an English (United States) instance of the CultureInfo class and stores a reference to the Type class, which describes the Excel. Range class. The call to rangeType. InvokeMember then uses reflection to explicitly set the Formula property of the passed range to the value of the passed formula. The key is that the call to InvokeMember includes the enUSCulture field, indicating that the value in the formula parameter should be parsed according the rules of English (United States) no matter what the current locale is. We see SetFormula in use when we populate the Account Summary worksheet.
WorksheetBase Properties.
WorksheetBase includes eight properties. As is commonly the case, four of these properties are simply accessors for a class field. For example, the RowCount is an integer serving as the accessor for the myRowCount field.
Table 7 describes the four properties that are simply accessors for member fields.
Table 7. WorksheetBase properties implemented as simple field accessors.
The number of data rows currently contained on the worksheet The value is specific to each worksheet.
True indicates that the worksheet is in the process of updating the display Used to avoid recursively handling worksheet-changed events when populating the display.
The currently selected range See the Worksheet_SelectionChange method later in this section for more information The ActiveRange value is specific to each worksheet.
Reference to the physical Excel 2003 worksheet managed by the derived class.
WorksheetBase also includes four read-only integer properties that return the first and last row and column of the range containing the worksheet data. These properties are FirstColumn , LastColumn , FirstRow , and LastRow . Each of these properties uses the columnSpanRange field created by the SetColumnSpanRange method. Remember that columnSpanRange is a range spanning the entire first row of data for the worksheet. This means the first column and row of the data can be found by simply accessing the Column and Row properties of columnSpanRange .
Determining the last column and row takes a little more effort, but not much. The Count property on columnSpanRange returns the number of columns in the range, so we can add that to FirstColumn to get the LastColumn property.
In the case of LastRow , we cannot get the number of rows from columnSpanRange because it is always a one-row range. We are still okay though, because the WorksheetBase class is already keeping track of the number of rows using the RowCount property. Therefore, adding the RowCount to the FirstRow gives us the LastRow .
Worksheet Activation and Selection.
The next WorksheetBase foundation member we look at is the ActivateSheet method. ActivateSheet handles the details of making a specific worksheet the active worksheet, including insuring that the worksheet is visible and that grid lines are not displayed. Hiding the grid lines is for aesthetics only.
Finally, we have the Worksheet_SelectionChange method that, of course, handles the worksheet's SelectionChange event. If you recall from the design discussion earlier, there are a number of situations where the stock allocation system must be selection-aware. For example, when the user clicks on the "Account Detail" toolbar button, the application must know the row of the current selection in order to determine with which account to populate the Account Detail worksheet. The Worksheet_SelectionChange method also calls the DoWorksheetSelectionChangeWork overridable (virtual) method to give derived classes an opportunity to do additional work. The WorksheetBase implementation of DoWorksheetSelectionChangeWork does not do anything.
The Worksheet_SelectionChange method and ActiveRange property work together. Worksheet_SelectionChange stores the selected range in the private field, myActiveRange , on each change; ActiveRange makes this range publicly visible.
Creating the Worksheets.
The WorksheetBase class provides a foundation for common worksheet operations, so we are now ready to start creating the worksheets.
When it comes to creating the worksheets, we have two jobs to perform because the worksheets actually have two somewhat distinct identities. For each worksheet in our application, there is the physical worksheet the user sees and interacts with and there is our Visual Basic class containing the code to manage the physical worksheet. You can create and format the physical worksheet either by using a Framework–based class to manipulate the Excel object model or by opening Excel 2003 and doing things interactively.
In general, I find that using Excel 2003 to do the worksheet creation and formatting tends to go much faster than writing Framework–based code to do the same thing. Any feature of the worksheets that is static in nature (such as headings, cell formats, etc.) can be performed interactively with Excel 2003.
Creating the Physical Worksheets.
In our stock allocation system, we have four distinct worksheets: Account Summary, Account Detail, Stock Summary, and Stock Allocation. Although not all worksheets may be initially visible, at run time we never have more then these four, so this is a perfect opportunity to use Excel 2003 as part of our application development. Using Excel 2003, we set up our project workbook, StockAllocation. xls, to have four appropriately named worksheets.
Note Visual Studio 2003 with Visual Studio Tools for Office does not support editing the Excel 2003 workbook from within the Visual Studio 2003 designer. This feature has been added to Microsoft Visual Studio Tools for Office 2005 Beta 1 with Microsoft Visual Studio 2005 Enterprise Edition Beta 1.
Setting up the worksheets in the StockAllocation. xls workbook is easy.
Open the StockAllocation. xls workbook in Excel 2003.
The newly created workbook looks similar to Figure 13.
The workbook now looks similar to Figure 14.
Figure 13. StockAllocation. xls containing default worksheets (click picture to see larger image)
Figure 14. StockAllocation. xls updated to contain the four required worksheets (click picture to see larger image)
Creating the Worksheet Classes.
Now that the StockAllocation. xls workbook has the physical worksheets, we are ready to create the Visual Basic classes that manage them. Creating the basic worksheet classes is simple because most of the standard housekeeping is handled by the WorksheetBase class from which each of the worksheet classes inherit.
The first worksheet class is AccountSummary , which of course inherits from WorksheetBase .
To access the reference to the Excel worksheet object, we need the worksheet name, "Account Summary." As part of good programming style, we want to minimize the literals used within the code, so we store the name of the worksheet as a constant, SHEET_NAME, within the class.
Finally, there is the class constructor. Remember, we want our worksheet class to store a reference to the Excel worksheet object. Our base class constructor knows how to access and store the Excel worksheet object if we give it the worksheet name; we just need to call the base class constructor and pass the SHEET_NAME constant.
Now, when the AccountSummary class is created, the WorksheetBase class locates the appropriate worksheet in the Excel object model and stores it in the myWorksheet member, making the worksheet available to the AccountSummary class through the inherited property, ExcelWorksheet .
The complete AccountSummary class looks like the following.
We now have a simple AccountSummary class. The project also contains classes for the other worksheets, named AccountDetail , StockSummary , and StockAllocation , with SHEET_NAME values of "Account Detail," "Stock Summary," and "Stock Allocation" respectively.
Getting It All Connected.
The last step is to instantiate our worksheet classes at application startup. This is done by the OfficeCodeBehind. ThisWorkbook_Open method, just after the call to Globals. InitApplicationAndWorkbook .
Making the Worksheets Available.
Like the Excel. Application and Excel. Workbook references, we need access to our worksheet class references throughout the application. Like the other references, we add the worksheet references to our Globals class.
For each worksheet class we need a Private, shared field to store the reference and a Friend, read-only shared property to expose the reference. Here are the members for the Account Summary worksheet.
We also need an initialization method to set the worksheet references.
We call the InitWorksheets method in OfficeCodeBehind. ThisWorkbook. Open right after we create the four worksheet classes. While we are adding code, we should go ahead and add exception handling.
Adding Navigation.
As an interactive application, the stock allocation system needs to provide some form of intelligent navigation. Having the user directly select a worksheet is fine as long as the worksheet already contains the desired data. With intelligent navigation, the stock allocation system can populate and display a worksheet based on the user's selection in another worksheet. For example, the stock allocation system displays a specific account's data in the Account Detail worksheet based on the user's current selection in the Account Summary worksheet, or selects the appropriate stock in the Stock Allocation worksheet based on the user's current selection in the Stock Summary worksheet.
In the stock allocation system, intelligent navigation is implemented using toolbar buttons at the top of the workbook. Toolbar functionality is exposed through the OfficemandBar control. Like the worksheets, the command bar is encapsulated in a Visual Basic class to simplify working with it.
The class is named ApplicationCommandBar . It contains a constant, COMMANDBAR_NAME, (to name the command bar) and a private field, myCommandBar (to hold the reference to the real command bar).
Now we need a constructor so that the real command bar is automatically created when our ApplicationCommandBar class is created. Command bars are exposed through the CommandBars collection on the Globals. ExcelApplication object, so we use the Globals. ExcelApplicationmandBars. Add method, specifying the command bar's name and that it should be docked at the top of the workbook. Being extra careful that we have no surprises, we explicitly set the command bar's Visible property to True.
Next, we need to put some buttons on the toolbar. We start with three buttons: one to update the stock price, one to display the stock allocation, and one to display the Account Detail. To do this, we need to declare three OfficemandBarButton objects. These should be declared WithEvents so that they have the ability to handle their click events.
We also need public, read-only properties for each button so that they can be accessed outside of the ApplicationCommandBar class. The properties are named UpdateStockPricesButton , StockAllocationButton , and AccountDetailButton . Here is the UpdateStockPricesButton property.
It takes a few lines of code to create a button and set all of the necessary properties. Since we are creating several buttons, we encapsulate the button creation in a method, AddButton .
The AddButton method accepts one String parameter, caption , and three Boolean parameters: beginGroup , visible , and enabled . beginGroup indicates whether we would like a separator between the button we are creating and the previous button on the toolbar. As the names imply, visible and enabled indicate whether the button should be initially visible and enabled.
Within the method, we create the button using the Add method of the myCommandBar. Controls collection, specifying the Office. MsoControlType. msoControlButton constant.
Finally, we set the button properties corresponding to the three function parameters and then return the button instance, as shown here in the complete AddButton method.
The three buttons are created within the ApplicationCommandBar constructor just after creating the command bar itself. The complete constructor now looks like this.
In addition to creating the command bar, we also need to be sure that our class supports cleaning up the command bar so that we can remove it at the end of our application. In Framework, classes requiring cleanup implement an interface named IDisposable. The IDisposable interface has just one method, Dispose .
Note For more information on Framework–based application cleanup guidelines and the IDisposable interface, see Implementing a Dispose Method.
To support cleanup, we have our ApplicationCommandBar class implement the IDisposable interface, adding the Dispose method to the class. Inside of the Dispose method, we delete the command bar object by calling myCommandBar. Delete .
Making the Command Bar Globally Available.
Like the worksheets, the command bar is used throughout the application, so we add it to our Globals class as well. In the Globals class, we create a private shared field, commandBarInstance , and a public shared property, CommandBar . We also include an InitCommandBar method.
Connecting the Command Bar.
We can now create the command bar and store it in the Globals class as part of OfficeCodeBehind. ThisWorkbook. Open , just before creating the worksheets.
We need to be sure to clean up the command bar when the application is being closed, so we call the command bar's Dispose method in the ThisWorkbook_BeforeClose method.
Making the Command Bar Context-Aware.
The "Account Detail" toolbar button is used to display the details of a specific account based on the user's selection on the Account Summary worksheet. Because the behavior is specific to the Account Summary worksheet, the button should only be visible when the Account Summary worksheet is active.
To make the "Account Detail" toolbar button context-aware, we need to display it when the Account Summary worksheet is activated and hide it when the worksheet is deactivated. We do this by adding methods to the AccountSummary class to handle the Activate and Deactivate events on the contained worksheet reference, myWorksheet . These methods set the state of the "Account Detail" button appropriately.
A Note on Defensive Programming.
We completed the basic functionality of the command bar and, as long as our application always shuts down cleanly, we are fine. However, if the program were to terminate abnormally, there is a possibility that the command bar may not be destroyed. As a result, when the program is next executed, the call to Globals. ExcelApplicationmandBars. Add to create the command bar throws an ArgumentException telling us that the parameter is incorrect, as shown in Figure 15. ArgumentExceptions can be thrown for many different reasons, but, in this case, it is an indication that the toolbar we are trying to create, "Stock Allocation Management," already exists.
Figure 15. Command bar ArgumentException message.
The best way I have found to deal with this scenario is to attempt to locate the command bar prior to creating it. If it exists, delete it. There is no built-in method to search for a command bar, so we write our own method to loop through the list of command bars, looking for the command bar with the appropriate name. To do this, we add the FindCommandBarInstanceByName method to the ApplicationCommandBar class.
If a command bar with the specified name already exists, FindCommandBarInstanceByName returns a reference to it; otherwise, the method returns Nothing. We can now add code to our ApplicationCommandBar constructor to search for an existing instance of our command bar and, if it exists, delete it. Here is the new ApplicationCommandBar constructor.
Now our command bar handling is stable and the command bar is always created correctly even if the prior execution did not clean up the command bar correctly.
Adding Data Management.
As mentioned earlier, we are using a Framework DataSet for data storage and management. The DataSet is read from and written to the local disk so that the application provides the user with a consistent experience whether in the office or out on the road.
Rather than use the DataSet class directly, the stock allocation system is using a typed DataSet, StockAllocationDataSet , which exposes specific properties for the contained tables and columns, rather than relying on the DataSet class's Tables property and GetXX methods. We talk more about the typed DataSet shortly in the "Data Model" section.
To encapsulate management of the DataSet, we have the DataSetUtility class.
DataSetUtility exposes a method to create the DataSet, populating it from the XML file. The implementation is simple because the DataSet provides a ReadXml method.
The GetFileName method is also part of the DataSetUtility class and handles the details of determining the fully qualified path of the XML data file.
Like the worksheet and command bar classes, we need to have access to the DataSet throughout the application—so we add the required field, property, and initialization method to our Globals class.
We also need to create and store the DataSet from the ThisWorkbook_Open method, just as we did with the worksheets and command bar. We can do this just after the command bar is created and stored.
Now we need the code to save and clean up the DataSet. First, we add a SaveDataSet method to DataSetUtilities , which uses the WriteXml function to write the new DataState to the XML file.
We, of course, also need to initiate the call to save the DataSet. To be consistent with the Excel 2003 user experience, we should save the DataSet just as Excel 2003 would normally save the workbook: when the user explicitly chooses the Save menu option or if the user attempts to exit Excel 2003 without explicitly saving. In our case though, we want to save the DataSet, not the workbook. We prevent the actual workbook from being saved by setting the Cancel property to True.
Now any time the user initiates a workbook save, whether explicitly by the user or implicitly by Excel 2003, our DataSet has its state saved to the StockAllocationData. xml file. The worksheet contents are never saved, which is also what we want, because we programmatically populate the worksheets using the DataSet contents each time the workbook is opened.
System Foundation Wrap Up.
We have invested a lot of effort in building wrappers around the worksheets, command bar, and DataSet, but it's time well spent. Every application involves addressing both technical and business issues. Encapsulating the technical details as we have allows us now to focus on the business issues. Minimizing the interference of technical details allows us to focus on the core business issues and therefore enables us to better solve the business problem, and generally leads to a higher-quality and easier-to-maintain solution.
The issues we have addressed in this foundation are common to many Visual Studio Tools for Office Excel projects and can be easily applied to most applications of this type. I find that it is worthwhile to back up a version of the project at its current point and use it as the starting point for other Visual Studio Tools for Office Excel project solutions.
Developing the Stock Allocation System Business Functionality.
Now that we have our application foundation in place, we are ready to begin building the business functionality into the system. Having invested in the foundation as we have, we can now focus on the required business features and minimize the time we spend on technical housekeeping.
The Data Model.
The data provided to our application resides in three relational tables.
ClientMaster: The master list of client accounts and related information. See Table 8 for the table schema. StockMaster: The master list of all stocks in the system along with their related information. This table is meant to represent all available stocks, not just those stocks actually owned by clients. In real life, this table would contain thousands of rows. See Table 9 for the table schema. ClientHoldings: The list of stocks owned by each client, including quantity owned and original purchase information. See Table 10 for the table schema.
Table 8. Table schema for the ClientMaster table.
Table 9. Table schema for the StockMaster table.
Table 10. Table schema for the ClientHoldings table.
These tables are exposed to the application through the typed DataSet class, StockAllocationDataSet , in Globals. DataSet . As a typed DataSet , StockAllocationDataSet is derived from the DataSet class and therefore has all of the same capabilities, but with the added bonus of being aware of our specific data model. As a typed DataSet , StockAllocationDataSet contains strongly typed class definitions for each of the three tables and exposes explicit properties for each. The tables in turn have explicit classes defined for the contained rows, with each column exposed as an appropriately typed property on the table.
StockAllocationDataSet was generated by passing the schema information from the StockAllocationData. xml file to the XSD. exe utility. The XSD. exe utility provides a number of class-generation and file-generation features, one of which is to generate a Typed DataSet class from an XML schema definition.
The DataSet is populated by the call to DataSetUtilities. CreateAndPopulateDataSet made from the ThisWorkbook_Open method, which reads the contents of the StockAllocationData. xml file. The DataSet maintains the relational structure of the tables so, even if you have never worked with the DataSet class, you are able to leverage your existing relational database knowledge.
Each of the worksheets retrieves its data from the DataSet, and any changes to the data are made within the DataSet. At the end of application execution, the current DataSet state is written back to the StockAllocationData. xml file using the DataSetUtilities. SaveDataSet method call made from the ThisWorkbook_BeforeSave method.
Formatting the Worksheets.
Now that we understand our data model, we can lay out the worksheets. Remember, the worksheets act as our application's user interface. We want to be sure that the user interface is both aesthetically pleasing and intuitive. The rich color, font, and layout features of Excel 2003 enable us to create a professional-looking application with relatively little work. Similar to creating the physical worksheets, formatting them is something most easily handled using Excel 2003 interactively.
A Technical Aside.
Before we actually begin formatting the worksheets, we need to deal with a technical aside. When we added the event handler for the workbook's BeforeSave event, we modified the behavior of Excel 2003 to save our DataSet but not the workbook contents as it normally would. Not saving the workbook contents includes not saving any format changes to the worksheets; as a result, any modifications we make to the worksheets interactively are lost. Although we do not want the workbook contents saved when we ultimately deploy the application, this is not a desirable behavior when we are formatting the worksheets.
After we go through the work of formatting the four worksheets, we want to be sure that formatting information is saved as part of the workbook. We can easily facilitate this by commenting out the code that is preventing the document from saving, which is the line setting the Cancel parameter to True in the ThisWorkbook_BeforeSave method.
We can add this line back in after we finish formatting the document.
With the ability to save the workbook contents restored, we can open the StockAllocation. xls file in Excel 2003 and start setting up the formats.
Note If you would rather not modify the code, there are a number of other options. For more information, see How to: Bypass the Assembly When Opening an Office Solution.
Formatting the Account Summary Worksheet.
First, we format the Account Summary worksheet (see Figure 16).
Figure 16. Account Summary worksheet formatting (click picture to see larger image)
In addition to the fonts, colors, and borders, we apply the following format settings.
Table 11. Formatting to apply to the Account Summary worksheet.
Figure 17. Excel 2003 Options dialog, disabling worksheet grid lines (click picture to see larger image)
Formatting the Account Detail Worksheet.
Figure 18 shows the formatted Account Detail worksheet.
Figure 18. Account Detail worksheet formatting (click picture to see larger image)
In addition to the fonts, colors, and borders, we apply the following format settings.
Table 12. Formatting to apply to the Account Detail worksheet.
Formatting the Stock Summary Worksheet.
Figure 19 shows the formatted Stock Summary worksheet.
Figure 19. Stock Summary worksheet formatting (click picture to see larger image)
In addition to the fonts, colors, and borders, we apply the following format settings.
Table 13. Formatting to apply to the Stock Summary worksheet.
Formatting the Stock Allocation Worksheet.
Figure 20 shows the formatted Stock Allocation worksheet.
Figure 20. Stock Allocation worksheet formatting (click picture to see larger image)
In addition to the fonts, colors, and borders, we apply the following format settings.
Table 14. Formatting to apply to the Stock Allocation worksheet.
Restoring the Previously Commented-Out Line of Code.
Once we have saved the worksheet format changes, we can restore the line we commented out in the ThisWorkbook_BeforeSave method.
Saving the workbook again saves only the DataSet , not the workbook contents.
Populating the Account Summary Worksheet.
We have data and we have formatted the worksheets, it is time to start populating the worksheets. Since Account Summary is the first worksheet the user views, that is where we start.
The Account Summary worksheet includes the account number, name, risk tolerance, current value, cash available, and profit/loss for each client account. Looking at the data model, we can see that with the exception of current value and profit/loss, all of the data can be found in the ClientMaster table. For the calculated columns, we need to use the ClientHoldings and StockMaster tables to calculate the values.
We start by defining constants for the worksheet positions.
Before populating the worksheet, we need to create named ranges for each data column. The named ranges serve as the reference point for adding data to the worksheet.
Once we create the named ranges, we can refer to them by either passing the string name of the range to the ExcelWorksheet. Range property or by storing the range reference returned by the WorksheetBase. CreateNamedRange method. Since each of the worksheet classes has a relatively small number of named ranges, and they are used frequently, we go ahead and store references to each as member fields in the AccountSummary class.
We then add a method, CreateInitialNamedRanges , to create the named ranges for each column based on the corresponding constants.
The named ranges are used throughout the AccountSummary class, so we create them in the class constructor. Once the ranges are created, they are passed to the WorksheetBase. SetColumnSpanRange method. Remember from our discussion back in the "Working with Ranges" subsection of the "Creating the Worksheet Foundation" section that passing the data display named ranges to the SetColumnSpanRange method allows WorksheetBase to determine the value of the properties FirstRow , LastRow , FirstColumn , and LastColumn .
To handle worksheet population, we add a Display method to the AccountSummary class. The Display method starts by making the Account Summary worksheet the active worksheet and then it calls a helper method I have added to the WorhsheetBase class, ClearContents , which takes care of the details of clearing any previous data from the worksheet. We also need some local variables.
Before writing the data to the worksheet, we need to expand the size of the area we formatted. You recall that we only formatted one row in the worksheet, so we need to increase the area to the number of rows contained in our ClientMaster table.
We already know most of the insert range because the call to SetColumnSpanRange in the constructor is all that is needed for the properties FirstRow , FirstColumn , and LastColumn to be valid. What we still need to know is the LastRow property. As you may recall, the implementation of the LastRow property adds the RowCount property to the FirstRow property. Therefore, assigning the row count from the ClientMaster table to the RowCount property gives us everything we need.
To do the insert, we create a range based on the row and column properties, and then we call the Insert method of the range. Specifying the parameter Excel. XlInsertFormatOrigin. xlFormatFromLeftOrAbove indicates that the new rows should have the same formatting and data validation as the row above the new range, thereby applying the cell formats we set interactively to the newly created rows.
Now that we know the row count, and therefore the location of the last row of data, we can create named ranges for the totals written at the bottom of the data area. We only need to create these ranges once, so we use a flag, firstDisplay , to avoid repeating the process.
The CreateTotalsNamedRanges looks very much like the CreateInitialNamedRanges method except that the ranges rely on the LastRow property rather than the STARTING_ROW constant.
We are now ready to write the actual data. The Account Summary worksheet is a listing of the rows contained in the ClientMaster table, so we could use the Rows collection, but we would have no control over the row order. We want to display the rows in order by ClientName , so we use the Select method, which allows us to specify the selection order. In addition to the selection order, the Select method requires that we pass a select condition; however, we want all of the records, so we just pass an empty string.
We can now loop through the rows writing the ClientMaster column values to the worksheet. By incrementing a row counter on each loop iteration, we write the data values as an offset from their corresponding named range.
As we loop through the accounts, we need to calculate the current value and profit/loss for each account. These values require data from the ClientHoldings and StockMaster tables. The ClientHoldings table contains the stocks owned by the account along with the purchase price; the StockMaster table has the current price of each stock. Using the Select method of the tables within the DataSet, we can easily extract the desired values from each.
The Select method accepts a selection criteria formatted similar to the Where clause portion of a SQL Select and returns an array containing the rows matching the criteria. To locate the list of holdings for the current ClientMaster record, we can issue a select against the ClientHoldings table for all rows for the current account.
To locate the price of the stock in the ClientHoldings table, we need to issue a select against the StockMaster table, looking for the current stock symbol. Looking up data for a stock symbol is a simple query, similar to the ClientHoldings query, but it occurs a number of times throughout the program, so I have encapsulated the code in the DataSetUtility. GetStockMasterRowForSymbol method.
Now that we know how to find all of the data, we can calculate the current value and profit/loss. To find the current value of the account, we loop through all of the account holdings, summing the product of the number of shares held and the current price; we then add in the cash available. In other words, the current value of the account is the total value of the stocks plus cash. To find profit/loss, we loop through the holdings, summing the product of the number of shares and the purchase cost of each stock; we then subtract that from the sum of the current value of each stock.
Bringing the data population steps together, here is the code that loops through the accounts, performs the necessary calculations, and writes to the worksheet.
With the accounts displayed, we now need to show the total value of all accounts, and the number of accounts. To show the total value of the accounts, we use the Excel 2003 Sum function to total the Current Value column. The currentValueRange. Column property returns the column as an integer, so we set the formula using the R1C1 format. We then use the WorksheetBase. SetFormula method to assign the formula to the cell referenced by totalValueOfBookRange .
For the number of accounts, we could just write the RowCount , but to make it more interesting, we use the Excel 2003 Count function. The Count function would be particularly useful if the application allowed the user to add more rows interactively. That behavior does not make sense in the case of our application, but it is useful in many cases.
To close the Display function, we call a helper function I added to WorksheetBase , FormatDataBorders , which draws the appropriate borders around the data cells. We then position the cell selection at the top of the worksheet.
We now have all the code to display the Account Summary screen data. We just need to add the code to ThisWorkbook_Open to call it. We can do this just after the call to Globals. InitWorksheets . We also add a call to the AccountSummary. ActivateWorksheet method to be sure that the Account Summary worksheet is the first displayed.
We now have a populated Account Summary worksheet.
Populating the Stock Summary Worksheet.
The Stock Summary worksheet provides a summary of all stocks in the money manager's book. Managing the Stock Summary layout is the same as the Account Summary; however, assembling the data is a little different because we need to calculate aggregate values for the number of shares and the number of accounts for each stock.
An easy way to calculate and write the aggregates is to use a traditional control-break model. Using a control-break model, we select all of the ClientHoldings records ordered by stock symbol. We loop through them, summing the shares and number of records; each time we encounter a new symbol, we write the totals.
We use the Select method to retrieve the ClientHoldings records, and specify that the records be ordered by stock symbol.
Within the loop, we can accumulate the number of shares and increment the number of accounts for each stock. Each time the stock changes, we write the totals for the previous stock using the WriteDisplayLine helper function I added to the StockSummary class, and we zero the counters.
How we handle inserting new rows is another key issue that is different from the Account Summary worksheet. In the Account Summary worksheet, it was easy to know the required number of display rows because it was equivalent to the number of records in the ClientMaster table. This enabled us to insert all of the new rows as a single range before starting the loop, which is very efficient.
In the case of the Stock Summary worksheet, there is no easy way to know the number of display rows in advance. We can't know how many unique stock holdings are in the ClientHoldings table without looping through the whole table, and we can't use the number of rows in the StockMaster table because it contains the available universe of all stocks, and therefore likely has thousands more stocks than are actually held in the book.
Because of this, it makes sense to insert each new row into the worksheet as needed. We insert each new row just after the previous row is written. We do the insert after writing a row, rather than before, because the worksheet starts with one row: the row we created interactively. Adding the new row after each row is written in the loop also addresses the fact that we cannot write the totals for the final stock until the loop completes.
Here is the whole Stock Summary data population loop, including the row inserts and final write.
Just like the Account Summary worksheet, we add the call to display the Stock Summary worksheet in the ThisWorkbook_Open method. We can add it just after the call to AccountSummary. Display .
Selecting and Displaying the Account Detail Worksheet.
Unlike the summary worksheets, the Account Detail worksheet displays on demand. To display an account, the user selects any cell in the Account Summary worksheet containing account data and clicks the "Account Detail" toolbar button. The Click event procedure extracts the selected account number from the Account Summary worksheet and initiates display of the Account Detail worksheet. Managing this process requires the involvement of the AccountSummary , ApplicationCommandBar , and AccountDetail classes.
The Role of the AccountSummary Class.
The first task for the AccountSummary class is to provide feedback to the user as to when it is valid to display an Account Detail worksheet. The AccountSummary class already provides some feedback by hiding the "Account Detail" button when the Account Summary worksheet is not active. We do this by handling the worksheet's Activate and Deactivate events.
We now need to provide feedback as to whether the current Account Summary selection is on an account row. We do this by setting the enabled state of the buttons based on the worksheet's current selection. The way to know the current selection is to handle the worksheet's SelectionChange event.
Remember, our base class, WorksheetBase , already handles the SelectionChange event. As part of the event handling, WorksheetBase calls an overridable method, DoWorksheetSelectionChangeWork , to give derived classes a chance to provide additional processing. As a reminder, here is the relevant code from the WorksheetBase class.
By overriding the DoWorksheetSelectionChangeWork method, AccountSummary adds the necessary processing to set the enabled state of the "Account Detail" button each time the user selects a different cell. A valid selection is between the FirstRow and LastRow . To avoid confusion, we also enforce that the selection cannot span multiple rows. Assigning the result of this condition to the button's Enabled property provides the desired result.
The other responsibility of the AccountSummary class is to provide the value of the selected account number. We use this to determine which account to display on the Account Detail worksheet. To provide this functionality, we add a SelectedAccountNumber property to the AccountSummaray class. The property simply returns the value in the account number column of the same row as the active selection.
Using a property to return the account number, rather than having the ApplicationCommandBar or AccountDetail classes read it directly from the worksheet, is a matter of maintainability. By using the property, the structure and behavior of the AccountSummary class are self-contained, shielding other classes from the details. In general, I find that limiting all reading and updating of the physical worksheet to the class managing the worksheet increases the stability and maintainability of the application.
The Role of the ApplicationCommandBar Class.
Because the ApplicationCommandBar class manages the "Account Detail" button, this is where we add the click event handler to display the Account Detail worksheet. In the event handler, we just retrieve the account number from the AccountSummary class and issue the call to the AccountDetail. Display method. We, of course, include some basic error checking and exception handling.
The Role of the AccountDetail Class.
The role of the AccountDetail class is to populate the Account Detail worksheet with the data of the selected account. Like the other worksheet classes, it provides a Display method, which populates the corresponding physical worksheet. The Display method implementation is consistent with the other worksheets with no substantial differences.
Applying Stock Allocations.
The Stock Allocation worksheet is the most interactive of the worksheets, accepting user input to determine the allocation criteria and allowing the user to override the calculated allocations by entering new values into the "Allocation to Apply" cells. Although slightly more involved than the other worksheets, the population and display code is still the same. What is different is that the Stock Allocation worksheet updates the data contained in the DataSet.
When the user clicks the "Apply Allocation" toolbar button, the DataSet is updated. The button click event is handled by the ApplicationCommandBar class, which ultimately calls the StockAllocation. ApplyAllocations method.
ApplyAllocations is responsible for the details of updating the DataSet. Primarily, this involves reading data from the Stock Allocation worksheet and adding new records to the ClientHoldings table. The first step is to declare local variables for the update values. We initialize the ones that are the same for all accounts, which are the price and purchase date. We do not need to read the symbol from the worksheet because it is stored in a class member variable, myStockSymbol .
Just like when updating the worksheets, we utilize named ranges to read the data.
On each loop iteration, we create a ClientHoldings row and update its values. We then store the row back in the table and subtract the cost of the allocation from the account's cash available.
We finish the function by displaying a success message to the user and updating the worksheets. To update the worksheets, we first call the OfficeCodeBehind. Refresh method, which tells each of the worksheets to re-read and display the DataSet data. We then call the StockAllocation. Display method with an empty stock symbol value, which clears the Stock Allocation display.
Updating the Stock Prices.
The final aspect of the implementation is the stock price update. The user can update the stock prices at any time by clicking the "Update Stock Prices" toolbar button. The button click is handled by the ApplicationCommandBar. updateStockPrices_OnClick method, which is responsible for initiating the process of retrieving the latest prices, then refreshing all of the worksheets so that they display the updated prices.
As mentioned in the architecture discussion, the stock allocation system retrieves the latest prices using a Java-based Delayed Stock Quote Web service provided by XMethods. We access the Web service using the netxmethodsservicesstockquoteStockQuoteService class, which we generated by selecting the Add Web Reference option on the Project menu of Visual Studio 2003 and typing the URL of the Web service's WSDL (services. xmethods/soap/urn:xmethods-delayed-quotes. wsdl) into the "URL" field of the "Add Web Reference" dialog.
Note For more information about accessing Web services with the Visual Studio 2003 Add Web Reference feature, see Adding and Removing Web References.
The netxmethodsservicesstockquoteStockQuoteService class handles all of the details of communicating with the Web service and makes updating the prices as simple as looping through the rows in the StockMaster table, updating the price of each.
The one complication is that the process of retrieving prices can be somewhat time consuming and this simple loop does not give the user visual feedback as to the progress. So, rather than perform this loop directly in the DataSetUtility. UpdateStockPrices method, DataSetUtility. UpdateStockPrices uses the UpdatePricesForm to retrieve the prices.
UpdatePricesForm is a Windows Form class that, when displayed, performs the same loop we saw earlier to retrieve the updated prices. The key difference is that it also displays a progress bar and the name of each stock as is retrieves the updated prices (see Figure 21).
Figure 21. UpdatePricesForm displaying progress bar and stock name.
Understanding Limitations of the Stock Allocation System.
Before we close, here are a few issues and limitations of the stock allocation system.
Business Behavior Limitations.
As I mentioned in the beginning of this paper, I based the stock allocation system on a portion of the business requirements for a real trade management system I previously wrote. If you are familiar with the brokerage industry or money management systems, you have likely noticed that the application avoids some of the more involved stock purchase issues. Obvious exclusions are support for buying on margin, multiple tax lots, partially filled orders, and average pricing. These and similar issues have intentionally been excluded to avoid introducing unnecessary complication into this example.
In the case of buying on margin, we treat all accounts as margin accounts, and we can therefore buy more shares than the number for which they have cash available. When applying an allocation to an account without sufficient cash, the whole allocation is applied and the account's cash available is set to zero.
The issue of multiple tax lots for a single stock does not come up because the allocation system excludes accounts already owning the stock being allocated from the allocation. This prevents an account from being allocated additional shares of a stock it already owns, and therefore prevents the account from having multiple tax lots for a single stock.
As for partial fills and average price, the system assumes that each account receives the allocated number of shares at the requested price. I realize that this is a bold assumption, but it is made to avoid unnecessarily complicating the sample.
Technical Limitations.
When developing the stock allocation sample system, I tried to make the sample easy to install, work with, and explore. For this reason, I excluded certain technical features that would appear in a real-life system.
One key issue has to do with users entering data into the worksheets. By the nature of this application, users are not expected to enter data into the system manually. In a real-life system any new data, such as a new client, would be retrieved from the enterprise database and would not be typed into the workbook by the user. For this reason, most of the stock allocation workbook would be protected to prevent users from manually entering or changing data. The accompanying solution leaves the workbook unprotected so that you can easily explore and modify it.
Finally, there is the issue of synchronizing the DataSet with a database. In real life, the stock allocation system would include functionality to support synchronizing the DataSet with the corporate database when connectivity is available. I did not include this functionality, in order to stay focused on the issues related to Visual Studio Tools for Office. Requiring database setup would also substantially complicate the set up and installation of the sample project. For information about synchronizing a DataSet with database contents, see Using a DataSet with Existing Data.
Potential Threats to Code Security.
The sample code included with this article is intended for instructional purposes, and should not be used in deployed solutions without modifications. In particular, you should take code security into greater consideration.
To illustrate the simplicity of this sample solution, a list of potential threats has been identified using the threat modeling process and tools described in the Threat Modeling section of the Microsoft Security Developer Center.
The following table gives some examples of the identified threats that you should take into consideration before expanding or deploying this solution.
Table 15. Identified threats against the sample solution.
File should be deleted if the component is no longer in use.
For information about code security, please visit the Microsoft Security Developer Center.
Conclusão.
With Visual Studio Tools for Office, we built a complete stock allocation system that takes advantage of the best that both Visual Studio 2003 and Excel 2003 have to offer. Visual Studio 2003 with the Framework 1.1 gives us the enterprise-level application development tools we need. It provides a platform that enables us to easily implement a smart client solution, giving the user access to their data from anywhere at any time, while helping us to leverage our existing development skills and knowledge of relational data. The integrated Web service support has enabled us to take advantage of a Java-based Web service to maintain up-to-date pricing from any available Internet connection with minimal effort.
Excel 2003 provides our application with a rich and highly interactive user interface right out of the box. The familiar Excel 2003 interface provides the user with the comfort of a familiar look-and-feel and reduces user-training time because users can take advantage of their existing Excel 2003 skills. The rich chart and graph capabilities of Excel 2003 also give users at-a-glance access to important information.
Visual Studio Tools for Office gives us the ability to work more efficiently by enabling us to merge the rich user experience provided by Office 2003 with the enterprise-level development tools provided by Visual Studio 2003 and the Framework 1.1.
Bring the Power of Visual Studio to Business Solutions Built with Microsoft Office: Get a good introduction to Visual Studio Tools for Office development with code samples in both Visual Basic and C#.
Creating XML Schemas and Datasets from Existing Data: See how to use the XSD. exe utility to generate typed DataSets and XML schemas.
How to: Bypass the Assembly When Opening an Office Solution: Learn about several options for opening a Word 2003 or Excel 2003 document without loading the associated assembly.
Adding and Removing Web References: See how to use the Web Reference feature of Visual Studio 2003 to access Web services.
Sobre o autor.
Jim Wilson is the president of JW Hedgehog, Inc., a New Hampshire–based consulting firm specializing in developing solutions for the Windows and Windows Mobile platforms. Jim has worked extensively with the Framework and the Microsoft Compact Framework since the original beta release of each. As a speaker, Jim can be seen at Tech Ed, VSLive, Microsoft Mobility DevCon, Embedded DevCon, and WinDev. He is co-founder of the New Hampshire User Group and is author of the MSDN online column titled You Can Take It With You.
No comments:
Post a Comment