Se tentar rodar a macro em outra posição se não a A1, vou acabar fazendo caca.
Excluindo a quinta coluna usando referências relativas:
Sub Macro2()
ActiveCell.Offset(4, 0).Rows("1:1").EntireRow.Select
Selection.Delete Shift:=xlUp
End Sub
Atalhos importantes:
Alt + F11: Abre o editor VBA.
Alt + Q: Fecha o editor VBA.
1.2 The Fundamentals of the Excel Object Model
+
Janela de verificação imediata:
Utilizada sempre que se deseja conhecer o valor de alguma variável usamos o ?:
?1 + 1
2
? Application.Name
Microsoft Excel
Referência completa acima, mas não preciso informar todas estas informações:
? Workbooks(1).Worksheets(1).Range("A1").Value
Goodbye
? Worksheets(1).Range("A1").Value
Goodbye
O conceito não é muito legal de usar, mas pode aparecer no código de outros
programadores.
Propriedades de objetos podem ser permissíveis para gravação ou não (somente
leitura).
? Workbooks(1).name
Teste-VBA.xlsm
? Workbooks(“Teste-VBA.xlsm”).name
Teste-VBA.xlsm
? Worksheets(1).name
Planilha1
Sub MyFirstProcedure()
End Sub
Sem espaços entre os nomes. Letras maiúsculas para cada nome distinto.
Immediate Window: Lugar ideal para testar um código.
? 2=2
Verdadeiro
Range("A1").Value = "Hi"
Posso utilizar o seguinte procedimento para obter um resultado na janela imediata.
Portanto, escrevo o código no Procedure do VBA e obtenho o resultado na janela
imediata:
Sub PrintStuffToConsole()
Debug.Print 1 + 1
End Sub
Janela imediata:
Hi
Goodbye
Procedure ficará parado enquanto o user não der o OK na janela que surgir, portanto
é necessário um certo cuidado ao usar tal função.
Ao colocarmos uma vírgula depois do valor do argumento, o VBA entenderá que o
segundo parâmetro será digitado.
Qualquer parâmetro entre [ ] são opcionais! Sem [ ] a inserção é obrigatória.
Usado quando quero misturar um user input com outro valor do programador. Uma
info pré-determinada e outra não.
Sub ShowBoxes()
VBA.MsgBox "Hello there"
VBA.MsgBox 2
VBA.MsgBox 3 + 5
VBA.MsgBox Range("A1").Value
End Sub
Comentários
Ignora parte do código.
Sub ShowBoxes()
'VBA.MsgBox "Hello there"
VBA.MsgBox 2 ‘Informa o número 2
VBA.MsgBox 3 + 5
'VBA.MsgBox Range("A1").Value
End Sub
Para fazer comentários em massa, recomenda-se ativar a seguinte janela:
Portanto, pode-se usar “ , “ para dar skip em um parâmetro que não for do interesse.
Object Browser -- F2
Códigos presentes: Livro verde voador: Método! A mãozinha no índice é uma
Propriedade!
Só clicar no ponto de pergunta amarelo para abrir a webpágina de ajuda. Posso
clicar em F1 também.
Invocar um Procedimento:
Option Explicit
Sub Annoy()
MsgBox "You did it!"
End Sub
? TypeName(Application)
Application
Útil futuramente em user forms, usuário insere um dado. Modo de descobrir qual o
tipo de objeto que o usuário escolheu.
? TypeName("Application")
String
Application.Workbooks(1).Worksheets(1).Range("A1").Value
=
Application.Workbooks(1).Worksheets(1).Range("B1").Value
End Sub
Fica então:
Option Explicit
Sub DoStuff()
Application.Workbooks(1).Worksheets(1).Range("A1").
Value = _
Application.Workbooks(1).Worksheets(1).Range("B1").Value
End Sub
Vai gerar um erro devido ao uso duplo de aspas. Tenho que usar mais um par de
aspas:
Debug.Print "Romeo said ""I love you Juliet"""
Variables:
Sempre colocar DIM antes de declarar uma variável. As logo após o nome dado
para a variável. Toda variável tem de ser declarada devido a Option Explicit.
Não podem conter espações e no máximo 256 caracteres. Sem caracteres especiais
e nomes já usados pelo VBA ou no Procedure. Age = age! Não diferencia letra maiúscula
e minúscula.
Option Explicit
Sub MyFirstVariable()
Dim Age As Integer
Age = 26
Debug.Print Age
MsgBox Age + 4
End Sub
Sub MoreVariableVariable()
Dim Age As Integer
Dim Lotterynumber As Integer
Dim SheetCount As Integer
End Sub
Mas se:
Sub MoreVariableVariable()
Dim Age, Lotterynumber, SheetCount As Integer
End Sub
Só Sheetcount é Integer. As outras são associadas para as variáveis VARIANT.
Bom usar long como variável para números inteiros
Option Explicit
Sub AssignSomeValues()
Dim b As Byte 'o to 255
Dim i As Integer '-32,768 to 32767
Dim l As Long '-2,147,484,648 to -2,147,484,647
b = 4
i = 25000
l = 1000000
MsgBox "b is: " & b & vbNewLine & "i is: " & i &
vbNewLine & "l is: " & l
End Sub
Operações matemáticas:
Option Explicit
Sub AssignSomeValues()
Dim a As Long
Dim b As Long
a = 4
b = 3
Debug.Print a + b
Debug.Print a - b
Debug.Print a * b
Debug.Print a / b
Debug.Print a Mod b 'Resto da divisão entre a e b
Debug.Print a ^ b
End Sub
Sub CalculateCircumference()
Dim pi As Double
pi = 3.14159
Debug.Print circumference
Debug.Print TypeName(circumference)
MsgBox "The circumference is " & circumference
End Sub
Sub TwoStrings()
Dim VariableName As String
Dim FixedName As String * 10
VariableName = "Boris"
FixedName = "Boris"
Debug.Print VariableName
Debug.Print FixedName
Debug.Print VariableName
Debug.Print FixedName
End Sub
Resultando em:
Boris
Boris
Boris Paskhaver
Boris Pask
Option Explicit
Sub TwoStrings()
Dim myBool As Boolean
myBool = False
Range("A1").Value = birthday
Dim lunch As Date
lunch = #12:30:00 PM#
Range("A2").Value = lunch
Dim SomeEvent As Date
SomeEvent = #6/30/2015 9:25:35 AM#
Range("A3").Value = SomeEvent
End Sub
Variant Data Type:
Capaz de se adaptar para guardar qualquer variável que for possível.
Option Explicit
Sub Chameleon()
Dim As Variant
a = True
Debug.Print TypeName(a)
a = 5
Debug.Print TypeName(a)
a = 3.14
Debug.Print TypeName(a)
End Sub
Sub ObjectVariables()
Dim wb As Workbook
Dim ws As Worksheet
Dim box As Range
Set wb = Workbooks(1)
Set ws = Workbooks(1).Janeiro
Set ws = wb.Janeiro
Set box = Workbooks(1).Janeiro.Range("B2")
Set box = ws.Range("B2")
Debug.Print wb.Name
ws.Name = "Fun Times"
box.Value = 5
End Sub
Default Values:
String = Empty String; Long e Double como zero; Boolean como True.
Option Explicit
Sub DefaultValues()
Dim s As String
Dim l As Long
Dim d As Double
Dim b As Boolean
Debug.Print s
Debug.Print l
Debug.Print d
Debug.Print b
End Sub
Resulta em:
0
0
Falso
1.6 Procedures
Scope: limite ou contexto que uma variável é permissível de existir. Três: Macro
Scope, Module Scope ou Application Scope. Exemplo:
Option Explicit
Sub ProcedureA()
Dim MyNum As Long
MyNum = 10
Debug.Print MyNum
End Sub
Sub ProcedureB()
Debug.Print MyNum
End Sub
MyNum foi declarado em outro procedure. As variáveis não se estendem além do
procedure. Assim, não gera erro:
Sub ProcedureA()
Dim MyNum As Long
MyNum = 10
Debug.Print MyNum
End Sub
Sub ProcedureB()
Dim MyNum As Long
MyNum = 50
Debug.Print MyNum
End Sub
Sub ProcedureA()
MyNum = 10
Debug.Print MyNum
End Sub
Sub ProcedureB()
Debug.Print MyNum
MyNum = 50
Debug.Print MyNum
End Sub
Sub ProcedureA()
MyNum = 10
Debug.Print MyNum
End Sub
Sub ProcedureB()
Debug.Print MyNum
MyNum = 50
Debug.Print MyNum
End Sub
Módulo 2
Sub ProcedureC()
Debug.Print MyNum ‘Tem o valor de 50 - ProcedureB
End Sub
Sub StepTwo()
Debug.Print "Second Step" ' Código de 40 linhas
End Sub
Sub Master()
'Business Logic
Call StepOne
Call StepTwo
End Sub
Sub WriteCalculation()
Dim mathCalc As Long
mathCalc = 5 * 4 * 3 * 2 * 1
LogMessageToConsole (mathCalc)
OutputMessage (mathCalc)
WriteValueToSheet (mathCalc)
End Sub
Os 3 primeiros códigos não executam nada por si só. Eles são invocados no último
módulo de tal forma a simplificar o código. Posso usar essa lógica se preciso fazer uma
tarefa várias vezes, como dar uma saída, escrever numa célula, etc.
Segredo é definir o parâmetro entre parênteses. Pode ser qualquer nome, mas
atenção na definição do tipo de variável.
Deixa explícito que é público para facilitar identificar futuramente no cenário com
public e private.
Private procedure existem para serem invocados por outros procedures!
Private Sub ExplicityPrivate()
Range("A1").Value = "Private stuff"
End Sub
O user não tem acesso a esse procedure, mas o usuário pode usar esse procedure
nos outros procedures a vontade!
Public Sub ExplicityPublic()
Call ExplicityPrivate
MsgBox 1 + 1
End Sub
Exit Sub
Termina um procedure se uma condição lógica é atingida
Se depende de um valor, e o usuário não fornece, faz sentido matar o processo.
Sub ExitEarly()
Debug.Print 1
Debug.Print 2
Exit Sub
Debug.Print 3
Debug.Print 4
End Sub
Constantes
Modo de associar uma variável para que ela não mude de valor.
Sub FunWithConstants()
Const PI As Double = 3.14159
Const cMonths As Long = 12
Const cTaxRate As Double = 0.0825
End Sub
Sub Occupation()
Debug.Print "I am a " & JobTitle
End Sub
Option Explicit
Sub ChangeOrientation()
Dim ps As PageSetup
Set ps = Worksheets("Sheet1").PageSetup
ps.Orientation = xlLandscape
End Sub
Sempre será usado quando a variável e o conteúdo não tiverem muita associação.
1.7 Object Deep Dive
DisplayAlerts Propriedades:
Relacionado com aquelas janelas que aparecem ao usuário. Pode ser interessante
desativar para melhorar a experiência ao usuário.
Sub CloseWorkbook()
Application.DisplayAlerts = False
Workbooks(1).Close
Application.DisplayAlerts = True
End Sub
Workbooks.Count e Worksheets.Count
Posso contar o número de Worksheets:
? Worksheets.Count
End Sub
WorkBooks.Close Method
Vai fechar todos os Workbooks!
Sub CloseEverything()
Application.DisplaysAlerts = False
Workbooks.Close
Application.DisplayAlerts = True
End Sub
Workbooks.Add Method
Igual a control + N.
Sub AddWorkbook()
Workbooks.Add
End Sub
Agora, se quero abrir um novo documento, tal que seja cópia idêntica de outro,
posso fazer:
Sub CreateNewWorkbook()
Workbooks.Add ActiveWorkbook.Path & "\teste.xlsm"
End Sub
Set w1 = Workbooks.Add
Set w2 = Workbooks.Add
w1.Worksheets(1).Range("C3").Value = "Red!"
w2.Worksheets(2).Range("E5").Value = "Blue!"
w1.Save
w2.Save
w1.Close
w2.Close
Application.DisplayAlerts = True
End Sub
Workbook.Activate Method
Ativa um Workbook - mesmo que clicar nele.
Sub MakingChanges()
Dim red As Workbook, blue As Workbook
Set red = Workbooks.Open(ThisWorkbook.Path &
"\red.xlsm")
Set blue = Workbooks.Open(ThisWorkbook.Path &
"\blue.xlsm")
red.Activate
ActiveWorkbook.ActiveSheet.Range("A1").Value =
"Another RED!"
blue.Activate
ActiveWorkbook.ActiveSheet.Range("A1").Value =
"Another BLUE!"
End Sub
Workbook.Close Method
Sub ClosingChanges()
Dim red As Workbook, blue As Workbook
Set red = Workbooks.Open(ThisWorkbook.Path &
"\red.xlsm")
Set blue = Workbooks.Open(ThisWorkbook.Path &
"\blue.xlsm")
red.Worksheets(2).Range("A2").Value = "Another
Another RED!"
blue.Worksheets(2).Range("A2").Value = "Another
Another BLUE!"
red.Close SaveChanges:=True
blue.Close SaveChanges:=False
End Sub
Workbooks.Add Method
Gerar uma nova planilha:
Sub GenerateNewWorksheet()
Worksheets.Add Before:=Worksheets("Planilha2")
End Sub
Worksheet.Visible Property
Permite ocultar planilhas!
Sub HideSomeSheets()
Worksheets(2).Visible = True
End Sub
Posso usar o Very Hidden para não possibilitar o user de acessar esses dados!
Sub HideSomeSheets()
Worksheets(1).Visible = xlSheetVisible
Worksheets(2).Visible = xlSheetHidden
Worksheets(3).Visible = xlSheetVeryHidden
End Sub
WorkSheet.Copy
Posso copier para uma nova planilha
Sub CopyWorkSheet()
Worksheets(1).Copy
End Sub
WorkSheet.Delete Method
Deletar uma planilha
Sub DeleteWorkSheet()
Application.DisplayAlerts = False
Worksheets("Planilha1").Delete
Application.DisplayAlerts = True
End Sub
WorkSheet.Move Method
Mover uma planilha de local:
Sub MoveWorksheets()
Worksheets(2).Move After:=Worksheets("Planilha2")
End Sub
? Range("A3").Text
R$9,99
? Range("A4").Text
quarta-feira, 13 de dezembro de 1995
Notação R1C1
Melhor para notações não tão fixas - Colunas e linhas encaradas como números
File - Options - Formulas - R1C1 Style (L1C1 no BR)
=L4C1
Células com valor em L5C3. Se estiver em L3C5, posso chamar o valor como:
=L[2]C
Se estiver em L9C3:
=L[-4]C
Se estiver em L5C1:
=LC[2]
Sub GetCellValues()
Debug.Print Range("A3").Value
Debug.Print Range("A3").Text
Debug.Print Range("A3").Formula
End Sub
Resize Property
Muda o tamanho de uma Range. Escolho o valor final que será mostrado. Assim,
por exemplo:
Range("C2").Resize(1,1).Select
Cells Property
Se baseia na notação R1C1
Objeto bem alto na hierarquia, assim, posso selecionar todas as células no
worksheet com:
Application.Cells.Select
Cells.Select
Só aceita uma id de linha e coluna - Usar resize para alterar para uma seleção maior:
Cells(2,5).Resize(4,5).Select
Cells(2,5).Resize(4,5).Value = "Fill"
? Range("A:A").Count
1048576
? Range("A1:XFD1").Count
16384
? Range("A:XFD").Count =======ERRO=========
? Range("A:XFD").CountLarge
17179869184
? Range("C4").Column
3
? Range("C4:J26").Column
3
Debug.Print Rows.Count
Debug.Print Columns.Count
End Sub
1048576
16384
Sub TargetStuff()
Columns(2).Select
Columns("B:D").Select
End Sub
Selecionando a segunda coluna de uma seleção (no caso seria a coluna C, até o
elemento C12):
Sub TargetStuff()
Range("B4:D12").Columns(2).Select
End Sub
Option Explicit
Sub TargetStuff()
Range("B4:D12").Columns(2).Select
Range("B4:C12").Rows(4).Value = "!"
End Sub
? ActiveCell.Address
$C$10
? activeCell.Row
10
? activeCell.Column
3
ActiveCell.EntireRow.Select
ActiveCell.EntireColumn.Select
Atenção que neste código, bagunçou tudo! Perdeu a relação entre os dados em A e
B. O seguinte código corrige o problema!
Sub SortColums()
Columns("A:B").Sort key1:=Range("B:B"), _
order1:=xlAscending, Header:=xlYes
End Sub
r.Font.Bold = True
r.Font.Italic = True
r.Font.Underline = xlUnderlineStyleDouble
r.Font.Size = 36
r.Font.Name = "Comic Sans MS"
r.Font.Color = vbRed
r.Font.Color = RGB(130, 55, 200)
End Sub
Cells(8,3).EntireRow.RowHeight = 45
Rows("2:5").RowHeight = 75
Ou resumindo:
Sub ClearStuff()
Range("A1:A3").Clear
End Sub
Range("C5").Delete xlUp
Sub CutAndPaste()
Range("B4:D6").Cut Destination:=Range("B8:D10")
End Sub
Range("C3").PasteSpecial xlPasteValues
End Sub
Parent Property
? TypeName(Range("A1").Parent) retorna:
Worksheet
? TypeName(Range("A1").Parent.Parent) retorna:
Workbook
? TypeName(Range("A1").Parent.Parent.Parent) retorna:
Application
1.10 Conditionals
Boolean Expressions
Valor verdadeiro ou falso. Exemplos de operadores e comparações:
? 3 < 5
Verdadeiro
? 4 < 1
Falso
? 5 <= 25
Verdadeiro
? 20 = 20 ‘Não é “==”!
Verdadeiro
Dim ft As Font
Set ft = rng.Font
ft.Size = 24
Posso usar quantos ElseIf quiser, mas prioirizar colocar os mais prováveis primeiro.
Se tudo acima for falso, posso usar em Else para continuar um código.
Sub ChangeFont()
Dim rng As Range
Set rng = Range("A1")
Dim ft As Font
Set ft = rng.Font
ft.Size = 24
Select Case
Coletar o que ainda está em D5:
Sub FunWithSelect()
Dim CurrentValue As String
CurrentValue = Range("D5").Value
And e Or:
Checando várias condições ao mesmo tempo:
Sub BoldHeaders()
If Range("A1").Value = "Name" Then
Range("A1").Resize(1, 2).Font.Bold = True
End If
End Sub
Sub BoldHeaders()
If Range("A1").Value = "Name" Or Range("B1").Value =
"Age" Then
Range("A1").Resize(1, 2).Font.Bold = True
End If
End Sub
Not Operator:
? Not True
Falso
Sub BoldSelection()
Range("B4").Resize(1, 3).Font.Bold = True
End Sub
1.11 Iteration
Sub SumTo25()
Dim Total As Long
Dim i As Long
Total = 0
For i = 1 To 25
Total = Total + i
Next i
MsgBox Total
End Sub
Step keyword
Não precisa de dar passos de 1 em 1:
Sub Step()
Dim i As Long
For i = 1 To 20 Step 2
Debug.Print i
Next i
End Sub
Sub ColorEverySecondRow()
Dim i As Long
Dim r As Range
Iteration backward
Muito usado para deletar linhas! Quando deleto com loop normal, as linhas sobem
e bagunçam tudo! Por isso, sempre que for deletar linhas, começar debaixo para cima!
Deletando linhas com DELETE: Segredo é usar STEP como -1:
Sub DeleteRows()
Dim FinalRow As Long
FinalRow = Cells(Rows.Count, 1).End(xlUp)
Dim i As Long
Dim ws As Worksheet
Exit For
Busca sair prematuramente:
Sub FindingAugust()
Dim LastRow As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
Dim i As Long
For i = 1 To LastRow
Cells(i, 1).Font.Name = "Comic Sans MS"
If Cells(i, 1).Value = "Agosto" Then
Cells(i, 1).Select
Exit For
End If
Next i
End Sub
Alterar o título:
Sub ShowBox()
MsgBox "I have custom buttons", vbQuestion +
vbYesNo + vbDefaultButton1, "Deletar?"
End Sub
Debug.Print response
End Sub
Status Bar
Aquela parte onde está escrito Ready. Posso dar opção ao user de ver o progresso
da Macro!
Sub StatusBarProcess()
Dim i As Long
For i = 1 To 20000
Cells(i, 1).Value = i * i
Application.StatusBar = False
End Sub
Dim I As Long
Dim J As Long
For I = 1 To 100
For J = 1 To 100
Cells(I, J).Value = I * J
Next J
Next I
Application.ScreenUpdating = True
End Sub
Special Cells
Selecionando só algumas células da seleção:
Selecionando só células com constantes:
Sub FindSpecificCells()
Dim r As Range
Set r = Range("A1:A10")
r.SpecialCells(xlCellTypeConstants).Select
End Sub
Células em vazio:
Sub FindSpecificCells()
Dim r As Range
Set r = Range("A1:A10")
r.SpecialCells(xlCellTypeBlanks).Select
End Sub
Fórmulas:
Sub FindSpecificCells()
Dim r As Range
Set r = Range("A1:A10")
r.SpecialCells(xlCellTypeFormulas).Select
End Sub
End Sub
1.13 Arrays
seasons(0) = "Summer"
seasons(1) = "Winter"
seasons(2) = "Fall"
seasons(3) = "Spring"
Debug.Print seasons(2)
End Sub
Alternate Syntax
Ajuda a ver lower e upper bound
Isso:
Sub LuckyNumbers()
Dim nums(5) As Long
nums(0) = 4
nums(1) = 7
nums(2) = 15
nums(3) = 16
nums(4) = 23
nums(5) = 42
End Sub
É idêntico a:
Sub LuckyNumbers()
Dim nums(0 To 5) As Long
nums(0) = 4
nums(1) = 7
nums(2) = 15
nums(3) = 16
nums(4) = 23
nums(5) = 42
End Sub
JustTheWeekend(1) = "Saturday"
JustTheWeekend(2) = "Sunday"
Debug.Print JustTheWeekend(2)
End Sub
JustTheWeekend(1) = "Saturday"
JustTheWeekend(2) = "Sunday"
Debug.Print JustTheWeekend(2)
Range("C1:D1").Value = JustTheWeekend
End Sub
For I = 1 To 10
wordArray(I) = Trim(Cells(I, 1).Value)
Next I
For I = 1 To 10
Cells(I, 2).Value = wordArray(I)
Next I
End Sub
Weekdays(0) = "Sunday"
Weekdays(1) = "Monday"
Weekdays(2) = "Tuesday"
Weekdays(3) = "Wednesday"
Weekdays(4) = "Thursday"
Weekdays(5) = "Friday"
Weekdays(6) = "Saturday"
Debug.Print LBound(Weekdays)
Debug.Pring UBound(Weekdays)
End Sub
Ou:
Sub ArrayofSun()
Dim Weekdays(6) As String
Weekdays(0) = "Sunday"
Weekdays(1) = "Monday"
Weekdays(2) = "Tuesday"
Weekdays(3) = "Wednesday"
Weekdays(4) = "Thursday"
Weekdays(5) = "Friday"
Weekdays(6) = "Saturday"
Debug.Print LBound(Weekdays)
Debug.Print UBound(Weekdays)
Dim I As Long
End Sub
Dynamic Arrays
Pegando o tamanho dos valores da coluna 1! Não importa o dia! Macro tem que
atender condições futuras.
Só não colocar número que o array vira dinâmico.
ReDim - Redimensiona o tamanho do vetor! Deleta todos os valores do Array! Usar
“ReDim Preserve” para conservar o valor.
Sub ArraysofValues()
Dim ColumnValues() As String
ReDim ColumnValues(FinalRow - 1)
Dim I As Long
For I = LBound(ColumnValues) To UBound(ColumnValues)
ColumnValues(I) = Cells(I + 1, 1).Value
Next I
1.14 Funções
Algumas funções disponíveis-armazenadas no Objeto VBA!
Tudo em minúsculas:
Sub FunWithVBAFunctions()
Debug.Print LCase("Hello")
Debug.Print Trim(" Hi! ")
End Sub
555
44
Exc
warts
555-555-5555
Split Function
Is Family
? isnumeric(5)
Verdadeiro
? IsNumeric(False)
Verdadeiro
? isdate("13/11/1992")
Verdadeiro
? isempty(Range("A1"))
Falso
3.14
Santa
Claus
TRUE
#DIV/0!
04/12/1991
Aplicando a subrotina:
Sub FigureOutCellType()
Dim I As Long
Dim LastRow As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
Dim val As Variant
Dim Calculations(3) As Boolean
For I = 2 To LastRow
val = Cells(I, 1).Value
Calculations(0) = IsNumeric(val)
Calculations(1) = IsDate(val)
Calculations(2) = IsEmpty(val)
Calculations(3) = IsError(val)
Cells(I, 2).Resize(1, 4).Value = Calculations
Next I
End Sub
23/07/2019
06:46:21
23/07/2019 06:46:21
Outras funções:
Sub CreateDates()
Debug.Print Year(Now)
Debug.Print Month(Now)
Debug.Print Day(Now)
Debug.Print Hour(Now)
Debug.Print Minute(Now)
Debug.Print Weekday(Now)
Debug.Print WeekdayName(Weekday(Now))
Debug.Print MonthName(Month(Now))
End Sub
2019
7
23
6
53
3
terça-feira
julho
Worksheet Functions
Vlook - Encontrando um salário da pessoa na célula selecionada, em uma tabela:
Sub VLookExample()
Dim cv As Variant
cv =
Application.WorksheetFunction.VLookup(ActiveCell.Value,
Range("A1:C5"), 3, False)
ActiveCell.Offset(0, 1).Value = cv
End Sub
Custom Functions
A função é adicionada a interface do Excel!
Function FtoC(temperature As Double) As Double
FtoC = (temperature - 32) * (5 / 9)
End Function
Sub Action()
Dim result As Long
result = FtoC(32)
Range("A1").Value = result
End Sub
Depurar - Compilar VBA Project para checar todos os Procedures por erros!
OnError e GoTo
Lembrar de usar Exit Sub!
Sub FunWithSum()
InvalidEntry:
MsgBox "Invalid cell value!"
End Sub
Error Object
0 significa que não erros - em Debug.Print Err.Number. Erro se mantém nas
iterações! Usar Err.Clear para não reter o valor.
Sub FunWithDivision()
Dim I As Long
If (Err) Then
Debug.Print Err.Number
Err.Clear
End If
Next I
End Sub
If (Err) Then
Debug.Print Err.Number
Debug.Print Error(Err.Number)
Err.Clear
End If
Next I
End Sub
For I = 1 To 100
Cells(I, 1).Value = Error(I)
Next I
End Sub
Breakpoints
Pausa a execução do código.
Basta clicar na barra esquerda do código - Linha fica na cor Bordô.
F9 coloca o Breakpoint e Shift+F9 retira o breakpoint.
1.16 Eventos
Responsáveis por dar trigger em uma macro, por exemplo. Quando adicionar um
valor na célula, execute uma macro.
Códigos não escritos mais nos Modules - Mas em Microsoft Excel Objetos -
Podendo limitar em uma planilha ou global!
Abrindo EstaPastaDeTrabalho - Escolhendo Objeto como Worksheet:
Private Sub Worksheet_SelectionChange(ByVal Target As
Range)
Review of Application.EnableEvents
Desativar um evento no começo e ativar depois! Evita Loops Infinitos
Private Sub Worksheet_SelectionChange(ByVal Target As
Range)
Application.EnableEvents = False
Cells.ClearFormats
Target.Interior.Color = vbBlue
Application.EnableEvents = True
End Sub
End Sub
Workbook Events and The Sh Argument
Sh é o nome padrão do Worksheet!
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal
Target As Range)
Application.EnableEvents = False
Dim ws As Worksheet
Set ws = Worksheets("Changes")
Application.EnableEvents = True
End Sub
Usar o padrão de definir três letras iniciais como código para identificação:
Fmr é Form
Lbl é label
Naming Conventions
Sempre inicio com o prefixo que indica o tipo de código! Inicia com o tipo de
controle, pois há diferentes métodos e objetos! Quando escrevo Procedures que vão
interagir com os User Forms - Necessário adotar um esquema de 3 letras para ajudar
futuramente.
Ajuda a associar objetos que estarão conectados!
Design Aesthetics
Todas opções em Formatar!
Como alinhar, etc.
Quando selectionado - O objeto que estiver com o envoltório com quadrados
brancos será o líder para que o alinhamento seja baseado!
The CommandButton Control
Dá um trigger em um procedure se quiser!
Código é CMD
Mas agora quero melhorar o Formulario para: não fechar automaticamente (tirar
UNLOAD ME) - e indicar ultimo valor inserido
Private Sub cmdSubmit_Click()
Dim LastRow As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
2
1
0
Lógica Final:
Private Sub cmdDelete_Click()
Application.DisplayAlerts = False
Dim I As Long
Check Box:
On-Off
Retorna booleano - V ou F
If Me.chkSave.Value Then
ActiveWorkbook.Save
End If
End Sub