Excel
Excel
Historico Excel
• Excel 2: The original version of Excel for Windows was called Version 2 (rather than 1)
so that it would correspond to the Macintosh version. Excel 2 first appeared in 1987.
• Excel 3: Released in late 1990, this version featured the XLM macro language.
• Excel 4: This version was released in early 1992. It also uses the XLM macro
language.
• Excel 5: This version came out in early 1994. It was the first version to use VBA (but it
also supports XLM). It's been years since I've heard from anyone who uses Excel 5.
• Excel 95: Technically known as Excel 7 (there is no Excel 6), this version began
shipping in the summer of 1995. It's rarely used anymore.
• Excel 97: This version (also known as Excel 8) was released in early 1997. It has
many enhancements and features a new interface for programming VBA macros. Excel
97 also uses a new file format (which previous Excel versions cannot open).
• Excel 2000: With this version, the numbering scheme jumped to four digits. Excel 2000
(also known as Excel 9) made its debut in June 1999. It includes only a few
enhancements from a programmer's perspective. Excel 2000 is rarely used.
• Excel 2002: This version (also known as Excel 10 or Excel XP) appeared in late 2001.
Perhaps this version's most significant feature is the capability to recover your work
when Excel crashes. Some people still use it.
• Excel 2003: Of all the Excel upgrades, Excel 2003 has the fewest new features. In
other words, most hard-core Excel users were disappointed with Excel 2003. As I write
this, Excel 2003 is still a commonly used version. It's also the last “pre-Ribbon” version of
Excel.
• Excel 2007: Excel 2007 signaled the beginning of a new era. Excel 2007 replaced the
old menu and toolbar interface and introduced the Ribbon. I was disappointed to discover
that you can't modify the Ribbon by using VBA. But this version of Excel had enough new
features to satisfy me, such as a new file format and support for much larger worksheets
— more than a million rows.
• Excel 2010: This version includes lots of new features (such as Sparkline graphics)
and performs quite a bit better in some areas. And if you need really huge workbooks,
you can install the 64-bit version. But again, I was disappointed because you still can't
modify the Ribbon using VBA.
• Excel 2013: The latest version is the one I used while writing this edition of the book.
Excel 2013 is available also in an online version (the Excel web app) and for devices that
run on Windows RT ARM-based devices. The Rib
Inserir função = Shift + F3
O excel tem uma analise inteligente, ele completa as celulas de acordo com um padrão
EX. coluna A nomes e sobrenomes, B nome - a partir do segundo ele vai completar com o
nome na sequencia, C sobrenome, ele completa com o sobrenome..
Formulas que fazem do excel um excel. se nao fosse isso, um word daria conta do recado
F9 - Calcula a planilha
Shift + F9 - Calcula só a aba
Relativo - referencia totalmente relativa. quando a formula é copiada, as celulas mudam para o
novo local EX A1
Absoluto - quando a celula é copiada, a célula referencia não muda $A$1
Linha Absoluta - a linha não muda A$1
Coluna Absoluta - a coluna não muda $A1
VBE
você só pode abrir com o excle aberto: alt +f11
Cada planilha é um projeto
MÓDULO
Editor
● Auto Syntax Check - faz correção automatica de erros
● Require Variable Declaration option - coloca a frase Option Explicit. Assim tem que
definir todas as variaveis que usar. Só afeta os novos modulos
● Auto List Members option - ele completa com algo que ele acha que é lógico
● Auto Quick Info option - ele mostra informalçoes sobre as funções e os argumentos que
voce digita
● Auto Data Tips option - displays the value of the variable over which your cursor is
placed when you’re debugging code
● Auto Indent setting - determines whether VBE automatically indents each new line of
code the same as the previous line
● Drag and Drop text editing option - copia e move texto apenas arrastando e soltando
com o mouse
● Default to Full Module View option - configura o status padrao para um novo modelo.
determina se VBE recua automaticamente cada
nova linha de código a mesma que a linha anterior
● Procedure Separator option - separa os codigos
CAPITULA 4
introdução ao objeto
OPP - object oriented programming
ideia é que o software consiste em distintos objetos que possuem atrubuições (ou
propriedades) e podem ser manipulados
O excel é um objeto que contém outros objetos que contem outros objetos. O VBA trabalha
com a hierarquia deles, sendo o proprio excel o objeto mae
Coleção
É um grupo de objetos do mesmo tipo
Exemplos comuns de coleção:
Referring Objects - 78
Every other object in Excel’s object model is under the Application object. You get to these
objects by moving down the hierarchy and connecting each object on your way with the dot (.)
operator. To get to the Workbook object named “Book1.xlsx”, start with the Application object
and navigate down to the Workbooks collection object.
Not far enough yet? If you really want to get the value from cell A1 on the first Worksheet of the
Workbook named Book1.xlsx, you need to navigate one more level to the Range object.
Application.Workbooks(“Book1.xlsx”). _ Worksheets(1). Range(“A1”).Value
Quando se referencia um objeto assim, é chamado de referencia totalmente qualificada. Você
falou para o excel exatamente onde você quer.
propriedades do objeto
propriedades são os atributos que descrevem o objeto. Como ele se parece, como ele se
comporta
(macros 1/2/3)
Métodos do objeto
Metodo é uma ação que você pode realizar com o objeto. o metodo pode mudar o objeto ou
fazer ele fazer alguma coisa
Objeto do evento
um objeto responde a eventos. Excel suporta vários eventos, mas nem todos objetos podem
responder a todos os eventos. e alguns objetos não respondem a nenhum evento.
cap 5
SUB X FUNÇÃO
SUB
começa com sub e termina com endsub. () vão depois do nome da macro.
Se a sub tem argumentos, listar eles dentro do parenteses
Quando grava uma macro, o resultado é sempre uma sub
Executando a Macro
- pela caixa de dialogo - Run. alt+f11
- atalho
- através de um botão (adicionar um botao: desenvolvedor - Controls - Insert), atribuir
macro
- através de uma outra macro (usar o call na formula)
Function
começa com fuction e termina com end fuction
Ex: Function CubeRoot(number) CubeRoot = number ^ (1 / 3) End Function
function só pode ser executada através de outra procedure ou usado com em uma formula na
planilha
*Para nomear
-pode se usar letras, numeros e algumas pontuações, mas o primeiro caracter tem que ser uma
letra
- não pode ter espaços
-VBA não distingue entre caixa alta ou baixa
- You can’t embed any of the following characters in a procedure name: #, $, %, &, @, ^, *, or !.
- até 225 caracteres
Ideal é que o nome descreva o proposito. Uma boa pratica é usar um nome e um verbo
GRAVAR MACROS
É a ideial para gravar macros simples, e de formatação. Somente para Sub e não para funções.
Não funciona para:
✓ Performing any type of repetitive looping
✓ Performing any type of conditional actions (using an If-Then statement)
✓ Assigning values to variables
✓ Specifying data types
✓ Displaying pop-up messages
✓ Displaying custom dialog boxes
CAP6
RELATIVE X ABSOLUTE
O excel padrão grava em referência absoluta na célula. E geralmente esse é o jeito errado de
gravar. Com gravação relativa, o excel fax referência relativa com as células
Gravando absoluto
1. Choose Developer➪Code➪Record Macro.
2. Type Absolute as the name for this macro.
3. Click OK to begin recording.
4. Activate cell B1 and type Jan in that cell.
5. Move to cell C1 and type Feb.
6. Move to cell D1 and type Mar.
7. Click cell B1 to activate it again.
8. Stop the macro recorder.
9. Press Alt+F11 to activate the VBE.
10. Examine the Module1 module.
Sub Absolute()
‘
‘ Absolute Macro
‘
Range(“B1”).Select
ActiveCell.FormulaR1C1 = “Jan”
Range(“C1”).Select
ActiveCell.FormulaR1C1 = “Feb”
Range(“D1”).Select
ActiveCell.FormulaR1C1 = “Mar”
Range(“B1”).Select
End Sub
Essa mesma ação acontece na célula que esta ativa quando você executa a macro.
Uma macro gravada usando referencia absoluta sempre produz o mesmo resultado
quando é executada. Nesse caso, sempre vai gerar um resultado no intervalo B1:D1
---------
------
OPÇÕES DE GRAVAÇÃO
✓ Briefly describe the purpose of each Sub or Function procedure you write.
✓ Use comments to keep track of changes you make to a procedure.
✓ Use a comment to indicate that you’re using a function or a construct in
an unusual or nonstandard manner.
✓ Use comments to describe the variables you use, especially if you don’t
use meaningful variable names.
✓ Use a comment to describe any workarounds you develop to overcome
bugs in Excel.
✓ Write comments as you develop code, instead of saving the task for a
final step.
-------------------
● Váriaveis
✓ You can use letters, numbers, and some punctuation characters, but the
first character must be a letter.
✓ You cannot use any spaces or periods in a variable name.
✓ VBA does not distinguish between uppercase and lowercase letters.
✓ You cannot use the following characters in a variable name: #, $, %, &, or !.
✓ Variable names can be no longer than 255 characters. Of course, you’re
only asking for trouble if you use variable names 255 characters long.
----------------------------------
O vba não requer que você declare as variavéis que você vai usar, mas é uma boa pratica
Se você não declara a variável, o Excel usa o padrão: Variante. Dados como variante ajem
como camaleões, eles mudam de acordo com o que você faz.
Declarando o tipo, otimiza a memória e a velocidade.
Para forçar a declaração de todas as variaveis, é interessante ativar o Option Explicit. Com ele
ativo, você não consegue execuar um codigo sem que todas as variaveis estejam declaradas
Procedure-only variables
The lowest level of scope for a variable is at the procedure level. (A procedure is either a Sub or
a Function procedure.) Variables declared with this scope can be used only in the procedure in
which they are declared. When the procedure ends, the variable no longer exists (it goes to the
great bit bucket in the sky), and Excel frees up its memory. If you execute the procedure again,
the variable comes back to life, but its previous value is lost.
Para declarar uma variavel, tem que colocar Dim (ele vem de dimensão, o qual significa
que você esta configurando a memoria para uma variavel particular. É usado depois da
Sub ou Function Procedure e antes do código
EX: Dim x As Integer
Quando não se classifica (EX: Dim y) o VBA utiliza o padrao, que é uma variante
-----
As Variaveis pública
Para declarar uma variavel para todo os procedimentos do VBA em uma planilha. Deve ser
inserido no início.
EX: Public CurrentRate As Long
As Variaveis Estaticas
Normalmente, quando um procedimento termina, todas as variaveis são resetadas.
Static Variables fazem com que o valor permaneça mesmo quando o procedimento termina.
Voce declara ela no começo.
Ela pode ser util se voce precisa controlar o numero de vezes de um procedimento.
Você pode declarar uma variável estática e incrementá-lo cada vez que você executar o
procedimento.
Ex;
O valor contar não é resetado quando o procedimento termina, mas é quando a planilha é
fechada.
Ela não é aceita para outros procedimentos. No exemplo, eles sao disoniveis somente dentro
do MySub. Em outras palavras, é uma variavel procedure-level.
De outra forma, somente procedure-level irão ser removidas da memoria quando a macro
termina de ser executada
----------------
LEMBRAR:
✓ To make a constant available within only a single procedure, declare the constant after
the procedure’s Sub or Function statement.
✓ To make a constant available to all procedures in a module, declare the constant in the
Declarations section for the module.
✓ To make a constant available to all modules in the workbook, use the Public keyword
and declare the constant in the Declarations section of any module.
Se tentar mudar o valor de uma constante na rotina VBA, ele vai gerar um erro (se essa
constante precisa mudar, ela é uma variavel e nao constante)
CONSTANTES PRÉ-DEFINIDAS
Excel tem muitas constantes predefinidas, qual voce pode usar sem precisar declarar ela
mesma. O gravador de macro geralmente usa constantes ao inves de valores atuais
Quando voce declara uma variavel com Dim, você pode especificar o máximo de caracteres, ou
deixar que o excel faça isso dinamicamente. Para especificar usar * N° (ex: Dim Testo As String
* 50). Quando essa valor nao é especificado, o excel que limita.
Quando você escreve no VBA você deve usar um dos formatos dos EUA (MM/DD/YYYY)
Quando você mostra a variavel (como em msgbox), VBA mostra usando a configuração do seu
sistema (se vc usa dd/mm/yyyy ele mostra dessa forma)