0% found this document useful (0 votes)
8 views15 pages

Excel

Atalhos e história sobre o excel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Excel

Atalhos e história sobre o excel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Cntr + F1 = oculta o menu

Pode-se adicionar atalhos rápidos (padrao é salvar, refazer e desfazer) - opções>barra de


acesso ráp>adicionar

Clicar no ALT gera letras para atalhos no teclado

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..

Cntl + 1 abre o formatar células

- Proteger a celula - Por padrão, todas as células são bloqueadas. (segundo


botao>formatar celulas>Proteção>desativar a caixa de bloqueio - OK >
Revisao>alterações>
- Senha para abrir - Arquivo>informações>proteger pasta de trabalho>criptografar
planilha

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

Referencia em outra aba - Nomedaaba!


Referencia em outra planilha - [Nomedaplanilha.xlsx]Nomedaaba!
Se a planilha possui espaços no nome - ‘[Nome da planilha.xlsx]Nome da aba’!
Se a planilha estiver fechada - =’C:\Pasta em que o arquivo esta\se tiver mais pasta separar por
\ \[Nome da planilha.xlsx]Nome da aba’!

- Para deletar os nomes na planilha


Sub DeleteHiddenNames()
Dim n As Name
Dim Count As Integer
For Each n In ActiveWorkbook.Names
If Not n.Visible Then
n.Delete
Count = Count + 1
End If
Next n
MsgBox Count & “ hidden names were deleted.”
End Sub

For example, assume that you have the following formula in


cell F10:
=A1–A2
If you define the names Income for A1 and Expenses for A2, Excel
doesn't automatically change your formula to
=Income-Expenses

Error Value Explanation


#DIV/0! - The formula is trying to divide by 0 (zero), an operation that's not
allowed on this planet. This error also occurs when the formula
attempts to divide by a cell that is empty.
#N/A - The formula is referring (directly or indirectly) to a cell that uses
the NA worksheet function to signal the fact that data isn't
available. A lookup function that can't locate a value also returns
#N/A.
#NAME? - The formula uses a name that Excel doesn't recognize. This can
happen if you delete a name that's used in the formula, if you
have unmatched quotes when using text, if you omit parentheses
for a function that uses no arguments, or if you misspell a
function or range name. A formula will also display this error if it
uses a function defined in an add-in and that add-in isn't
installed.
#NULL! - The formula uses an intersection of two ranges that don't
intersect. (This concept is described in the section “Intersecting
names,” earlier in the chapter.)
#NUM!
A function argument has a problem; for example, the SQRT
function is attempting to calculate the square root of a negative
number. This error also appears if a calculated value is too large
or too small. Excel doesn't support nonzero values less than 1E–
307 or greater than 1E+308 in absolute value.
#REF! The formula refers to a cell that isn't valid. This can happen if a
cell used in a formula has been deleted from the worksheet.
#VALUE!
The formula includes an argument or operand of the wrong type.
An operand is a value or cell reference that a formula uses to
calculate a result. This error also occurs if your formula uses a
custom VBA worksheet function that contains an error.
#####
A cell displays a series of hash marks under two conditions: The
column isn't wide enough to display the

Home⇒Editing ⇒Find & Select⇒Go to Special - para localizar coisas na planilha

VBE
você só pode abrir com o excle aberto: alt +f11
Cada planilha é um projeto

MÓDULO

In general, a VBA module can hold three types of code:


✓ Declarations: One or more information statements that you provide to
VBA. For example, you can declare the data type for variables you plan
to use, or set some other module-wide options.
✓ Sub procedures: A set of programming instructions that performs some
action.
✓ Function procedures: A set of programming instructions that returns a
single value (similar in concept to a worksheet function, such as SUM).

3 maneiras de usar o VBA

✓ Enter the code directly.


✓ Use the Excel macro recorder to record your actions and convert them to VBA code (see
Chapter 6).
✓ Copy the code from one module and paste it into another.

CUSTOMIZAR O AMBIENTE VBA

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:

✓ Workbooks: A collection of all currently open Workbook objects


✓ Worksheets: A collection of all Worksheet objects contained in a particular Workbook object
✓ Charts: A collection of all Chart objects (chart sheets) contained in a particular Workbook
object
✓ Sheets: A collection of all sheets (regardless of their type) contained in a particular Workbook
object

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.

Atalhos: o Application já é sempre assumido pelo VBA.


Se você tem certeza que esta na planilha ativa, você também não precisa referênciar ela. O
mesmo funciona com a aba

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 procedure é um grupo no VBA que realiza uma ação no Excel


Function é um grupo do VBA que realiza algum calculo e retorna a um valor singular

A maioria é sub (execute alguma coisa e alguma coisa acontece)

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

Ex: Sub ShowMessage() MsgBox “That’s all folks!” End Sub

Executando uma sub: maneiras


✓ With the Run➪Run Sub/UserForm command (in the VBE). Excel executes the Sub
procedure in which the cursor is located. This menu command has two alternatives: the F5 key
and the Run Sub/UserForm button on the Standard toolbar in the VBE. These methods don’t
work if the procedure requires one or more arguments. ✓ From Excel’s Macro dialog box. You
open this box by choosing Developer➪Code➪Macros or by choosing View➪Macros➪Macros.
Or bypass the Ribbon and just press the Alt+F8 shortcut key. When the Macro dialog box
appears, select the Sub procedure you want and click Run. This dialog box lists only the
procedures that don’t require an argument. ✓ Using the Ctrl+key shortcut assigned to the Sub
procedure (assuming you assigned one). ✓ Clicking a button or a shape on a worksheet. The
button or shape must have a Sub procedure assigned to it. ✓ From another Sub procedure that
you write. ✓ From a button that you’ve added to the Quick Access toolbar. (See Chapter 19.) ✓
From a custom item on the ribbon you develop. (See Chapter 19.) ✓ Automatically, when you
open or close a workbook. (See Chapter 11.) ✓ When an event occurs. As I explain in Chapter
11, these events include saving the workbook, making a change to a cell, activating a sheet, and
other things. ✓ From the Immediate window in the VBE. Just type the name of the Sub
procedure and press Enter.

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

1. Determine what you want the macro to do.


2. Get things set up properly.
This step determines how well your macro works.
3. Determine whether you want cell references in your macro to be relative
or absolute.
4. Click the Record Macro button in the left side of the status bar (or
choose Developer➪Code➪Record Macro).
Excel displays its Record Macro dialog box.
5. Enter a name, shortcut key, macro location, and description.
Each of these items — with the exception of the name — is optional.
6. Click OK in the Record Macro dialog box.
Excel automatically inserts a VBA module. From this point, Excel converts
your actions into VBA code. It also displays a Stop Recording
button on your status bar (a blue square).
7. Perform the actions you want recorded by using the mouse or the
keyboard.
8. After you’re finished, click the Stop Recording button on the status
bar (or choose Developer➪Code➪Stop Recording).
Excel stops recording your actions.
9. Test the macro to make sure it works correctly.
10. As an option, you might want to clean up the code by removing extraneous
statements.

É 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

O sucesso do gravação depende de cinco fatores:

✓ How the workbook is set up while you record the macro


✓ What is selected when you start recording
✓ Whether you use absolute or relative recording mode
✓ The accuracy of your recorded actions
✓ The context in which you play back the recorded macro

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

GRAVANDO REFERÊNCIA RELATIVA


Mudar clicando no Use Relative Referencias no grupo de Código na aba de Desenvolvedor.
Esse é um botão de alternar. quando esta em diferente cor, o modo de gravação é o relativo.
Quando esta na mesma cor, o modo de gravação é o absoluto. Pode mudar a maneira em
qualquer tempo, mesmo no meio da gravação.

1. Activate cell B1.


2. Choose Developer➪Code➪Record Macro.
3. Name this macro Relative.
4. Click OK to begin recording.
5. Click the Use Relative References button to change the recording
mode to relative.
When you click this button, it changes to a different color than the rest
of the ribbon.
6. Activate cell B1 and type Jan in that cell.
7. Move to cell C1 and type Feb.
8. Move to cell D1 and type Mar.
9. Select cell B1.
10. Stop the macro recorder
Sub Relative()

‘ Relative Macro

ActiveCell.FormulaR1C1 = “Jan”
ActiveCell.Offset(0, 1).Range(“A1”).Select
ActiveCell.FormulaR1C1 = “Feb”
ActiveCell.Offset(0, 1).Range(“A1”).Select
ActiveCell.FormulaR1C1 = “Mar”
ActiveCell.Offset(0, -2).Range(“A1”).Select
End Sub

A macro sempre começa na célula que esta ativa

---------

é legal gravar e analisar ao mesmo tempo (dividir a tela em dois, minimizar)

------

OPÇÕES DE GRAVAÇÃO

Quando for gravar, há diversas opções.


- Nome da macro (padrão macro1, macro2). Eu só mudo quando a macro der certo.
- atalho (para minusculas ctrl + letra e para maiuculas ctrl + shift + letra)
- Local da gravação (padrão é na planilha ativa)
- Descrição do que a macro faz
-
- PARTE III - PROGRAMANDO CONCEITOS

USAR COMENTÁRIOS NO CÓDIGO VBA


O vba ignora esses comentários, então pode-se escrever qualquer coisa.
Tem que ter um apóstofro na frente. O VBA ignora qualquer coisa depois de um apostofro. Só
não ignora dentro de aspas.

Para colocar um bloco em comentários (util para “separar” um código) ir em exibir-barra de


ferramentas-editar-inserir comentário.

Dicas para usar os comentários de forma efetiva:

✓ 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.

-------------------

USANDO VARIAVEIS, CONSTANTES E DADOS

O principal próposito do VBA e manipular dados.

● Váriaveis

Uma variável é simplesmente um local de armazenamento nomeado na memória de seu


computador. Você assimila o valor de uma váriavel através do =

Regras para os nomes das variaveis:

✓ 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

DECLARANDO O ESCOPO DA VARIAVEL

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

Pode-se declarar tbm várias variaveis com o mesmo Dim


Ex: Dim x As Integer, y As Integer, z As Integer (não pode x, y, z As Integer)

Para declarar para todos os procedimentos do modulo, devemos classificar a Dim no


começo do modulo, junto com o Option Explicit.

-----

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.

Vida das Variaveis


O escopo da variavel nao determina só onde a variavel pode ser usada, mas também em qual
circunstancia ela pode ser deletada da memória.

Você pode extermir a variavel da memoria através de 3 metodos:


✓ Click the Reset toolbar button (the little blue square button on the Standard toolbar in the
VBE).
✓ Click “End” when a runtime error message dialog box shows up.
✓ Include an End statement anywhere in your code. This is not the same as an End Sub or End
Function statement.

De outra forma, somente procedure-level irão ser removidas da memoria quando a macro
termina de ser executada

----------------

Trabalhando com constantes


Uma variavel pode mudar enquanto o procedimento esta sendo executado (isso é o pq
chamamos de variavel). Algumas vezes tu precisa se referir a um valor ou a um texto que
nunca muda. Nesse caso, você precisa de uma constante - um elemento que nunca muda.
EX:

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

TRABALHANDO COM TEXTO


Se pode trabalhar com dois tipos de texto:
● Fixed-length strings are declared with a specified number of characters. The maximum
length is 65,526 characters.
● Variable-length strings theoretically can hold as many as two billion characters

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.

TRABALHANDO COM DATAS


Voce pode usar String para armazenar datas, mas ela nao ira fazer calculos.

Data pode conter qualquer data entre 01/01/100 até 31/12/9999.

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)

You might also like