BASIC OF VBA
to start programming, lagi dapat na
sub NAMENGTITLE ()
To insert a commant, use " ' " it will be indicated in green and not be part of the
code
*BASIC VBA SENTENCES*
object.method (first is define mo muna ano yung object tapos full stop represent
by " . "
then yung method na gusto mong gawin sa object
*Example on how to add titles on cells*
Range("A1").Value = "Created By"
*Example on how to add values to cells*
Range("A2").Value = Environ("Username") - para ma input yung username ng pc
Range("B2").Value = date - para ma input yung date today
*Example on how to Format cells*
Range("A1:A3").Font.color = vbBlue
Range("A1:A3").Interior.color = rgbLightCyan
*How to select a cell and input data on it*
Worksheets("Sheet1").Range("A3").Select
ActiveCell.Value = 11
*How to include data infinitely*
Range("B3",range("B3").End(xlDown))
*How to Find The end list and offset cells*
Worksheets("Sheet1").Range("A1").End(xlDown).Offset(1,0).Value = 13
*Keyboard ShortCut*
Ctrl+Spacebar - para mag pop up lahat ng mga commands
*Ctrl + space bar and then len command is short for length*
len(FilmName
*When we sa int it will return a whole number*
*When we say mod it will return the remainder of the divided number*
___________________________________________________________________________
VARIABLES
*What is variable*
Basically dito na iistore yung information na nilagay mo
*It is necessary to declare variable?*
Yes to prevent possible misspell errors in the future
*How to declare variable?*
dim NewFilmName as string
*How to connect two subroutine code?*
Call "Input pangalan ng Sub"
*Declare variables before sub routine or after option explicit for it to recognized
in whole module*
*Use public instead of dim if you want the variables to declare even in other
modules*
*Other things is pag public instead of dim ginamit na reretain yung value ng
variable unlike sa dim na nagrereset*
*What is object Variable?*
Dito ang ginagawa is kaya niya mag store ng information sa different object or
range
*How to declare and set object variable?*
dim FilmNameCells as Range
Set FilmNameCells = Range("B2:B13")
FilmNameCells.Font.Color = rgbBlue
*How to store new objects in new worksheets?*
Dim MyNewsheet As worksheet
Worksheets.Add
Set MyNewsheet = ActiveSheet
___________________________________________________________________________
MESSAGE BOXES
*How to Input a message*
Msgbox "I like pizza"
*To join text together use " & "
*How to Put message in the next line?*
Msgbox "I am groot" & vbNewLine & "No you are not"
*How to display message on cell values*
Range("B12").select
Msgbox Activecell.Value & " was released on " & ActiveCell.offset(1,0).Value
*How to display answer to a question in Msgbox?*
Msgbox "Do you like pizza?", vbQuestion + vbYesNo, "Food Question"
*How to store the result of msgbox?"
Dim ButtonClicked As VbMsgBoxResult
ButtonClicked = MsgBox("Do you like pizza?", vbQuestion + vbYesNo, "Food
Question")
if ButtonClicked = vbYes then
Msgbox "Yes, Pizza are my favorite!"
Else
Msgbox "Why not? are you tongue stupid?"
End if
___________________________________________________________________________
INPUT BOXES
*How to capture the results of InputBox*
Dim YourName As string
YourName = inputbox ("Please type your name")
Msgbox "Hello " & YourName
___________________________________________________________________________
*How to convert data types?*
Dim strFilmDate as string
Dim datFilmDate as Date
strFilmDate = inputbox("Type the Released Date")
If strFilmDate = "" then
Msgbox "You didn't Enter a Valid date"
Exit Sub
End if
datFilmDate = CDate(strFilmDate)
___________________________________________________________________________
APPLICATION INPUT BOX
*Advantage of application.inputbox *
Yung mga limitation sa inputbox kaya ma gawan ng paraan sa application.inputbox
Kusa narin mag kakaron ng for example : You did not enter a valid number, etc.
Unlike sa inputbox na i cocode mo pa yung output na yan
*Code niya is application.inputbox*
*How to return a reference to multiple cells?*
Dim CopyRange as range
Dim PasteDestination as range
Set CopyRange = application.inputbox(Prompt:="Choose Cells to Copy, Type:= 8)
Set PasteDestination= application.inputbox(Prompt:="Choose Cells to Paste,
Type:= 8)
CopyRange.copy PasteDestination
___________________________________________________________________________
WITH STATEMENT
*useful siya pag finoformat mo yung mga cell kasi pwedeng di mo na siya paulit ulit
na irefer*
With Range("C3:C15")
.Font.Color = vbBlue
.Font.Italic = True
End With
___________________________________________________________________________
LOOP
*Do while or Do until depends on your codes*
*How to do simple loop?*
Range("A3").select
Do
Activecell.Offset(1,0).Select
Loop
*How to end Do Loop command?*
Range("A3").select
Do until Activecell.Value = ''
Activecell.Offset(1,0).Select
Loop
or
Range("A3").select
Do
Activecell.Offset(1,0).Select
Loop Until Activecell.value = ""
*How to exit Do loop?*
Range("A3").select
Do
if Activecell.Value = 0 then exit do
Activecell.Offset(1,0).Select
Loop
*How to run code faster when using Loop?*
Before the Do function type application.Screenupdating = false
and then after loop function type application.screenupdating = true
*How to turn off copy selection when loop ends?*
After Loop function type Application.CutCopymode = false
___________________________________________________________________________
FOR NEXT LOOP
*what is loop counter?*
to specify how many times you want your loop to run
*what is Step Keyword*
So that you can control how your loop counter is incremented o decremented
*What is the syntax for loop counter?*
Dim LoopCounter As Integer
For LoopCounter = 1 To 10
Debug.Print "LoopCounter = " & LoopCounter
Next LoopCounter
*What if you want to increment it in 2 numbers?*
Dim LoopCounter As Integer
For LoopCounter = 1 To 10 step 2
Debug.Print "LoopCounter = " & LoopCounter
Next LoopCounter
*How to exit from next loop?*
Option Explicit
Sub SimpleForNextLoop()
Dim LoopCounter As Integer
Dim RandomNumber As Double
For LoopCounter = 1 To 10 Step 1
Debug.Print "LoopCounter = " & LoopCounter
RandomNumber = Math.Rnd
If RandomNumber > 0.7 Then Exit For
Next LoopCounter
End Sub
___________________________________________________________________________
FOR EACH NEXT LOOP
*What is For each next loop*?
It allows you to loop over all of the objects in a collection
*Syntax For each next loop*
Sub ListOfWorksheetNames()
Dim SingleSheet As Worksheet
For Each SingleSheet In Worksheets
SingleSheet.Unprotect
Next SingleSheet
End Sub
*How to loop over cells?*
Sub LoopOverCells()
Dim SingleCell As Range
Dim ListofCell As Range
Set ListofCell = Range("A3", Range("A3").End(xlDown))
ThisWorkbook.Activate
Range("E3").Select
For Each SingleCell In ListofCell
If SingleCell.Offset(0, 3).Value < 100 Then
ActiveCell.Value = "Short"
ActiveCell.Offset(1, 0).Select
ElseIf SingleCell.Offset(0, 3).Value < 120 Then
ActiveCell.Value = "Medium"
ActiveCell.Offset(1, 0).Select
Else
ActiveCell.Value = "Long"
ActiveCell.Offset(1, 0).Select
End If
Next SingleCell
*How to do Nested for each loops?*
dim SingleBook as Workbook
dim SingleSheet as Worksheet
for each Singlebook in Workbooks
for each SingleSheet in Singlebook.Worksheet
SingleSheet.Protect
next SingleSheet
Next SingleBook
___________________________________________________________________________
FIND
*How to use find accurately and in whole words*
Range("B3:B15").Find(What:="Ted", Matchcase:=True, LookAt:=xlWhole).Select
*How to find nothing*
Dim FilmCell As Range
Set FilmCell = Range("B3:B15").Find(What:="Brave", MatchCase:=True
LookAt:=xlWhole,)
If FilmCell Is Nothing Then
MsgBox "Nothing is Found"
Else
FilmCell.Select
End If
*How to use FindNext*
Dim FilmName As String
Dim FilmCell As Range
Dim SearchRange As Range
Dim FirstCell As String
FilmName = Application.InputBox( _
Prompt:="Type the name of film", Type:=2)
Set SearchRange = Range("B3", Range("B3").End(xlDown))
Set FilmCell = SearchRange.Find _
(What:=FilmName, MatchCase:=False, LookAt:=xlPart)
If FilmCell Is Nothing Then
MsgBox "Nothing is found"
Else
FirstCell = FilmCell.Address
Do
MsgBox FilmCell.Value & " is released on " & _
FilmCell.Offset(0, 1).Value
Set FilmCell = SearchRange.FindNext(FilmCell)
Loop While FilmCell.Address <> FirstCell
End if
End Sub
___________________________________________________________________________
FUNCTION
*What is a function?*
A function is simply a procedure which returns a value and come in handy
whenever you find yourself writing out the same calculations again and again
*Syntax for function*
Function CustomDate() As String
CustomDate = Format(Date, "dddd dd mmmm yyyy")
End Function
Sub CreateNewWorkSheet()
Worksheets.Add
Range("A1").Value = "Created on " & CustomDate
End Sub
*How to add parameters to the function*
Function CustomDate(DateToFormat As Date) As String
CustomDate = Format(DateToFormat, "dddd dd mmmm yyyy")
End Function
Sub CreateNewWorkSheet()
Worksheets.Add
Range("A1").Value = "Created on " & CustomDate(#8/6/1998#)
End Sub
*Optional parameters must come after the primary paramaters*
___________________________________________________________________________
EVENT PROCEDURES
*What is event procedures?*
is simply a sub routine which runs itself automatically in response to a
certain events
*Example on how to cancel event*
Private Sub Workbook_BeforeClose(Cancel As Boolean)
MsgBox " Who told you to leave!!!?? "
Cancel = True
End Sub
___________________________________________________________________________
ARRAY
*what is an array?*
An array is like a variable which you can store more than 1 value using the
same
variable name
*Option base 1*
para sa 1 mag simula yung count ng array at hindi sa fixed na 0
*Syntax for array na cincosinder na 3 variables nakastore doon*
Sub FixedArray()
Dim TopThreeList(1 To 3) As String
End Sub
*What is multidimensional array*
It is when you can store variables in spreadsheet in multi direction like not
only on the
columns but as well as rows
*Syntax for multidimensional array*
Sub MultiDimensionArray()
Dim TopTenFilms(0 To 9, 0 To 5) As Variant
TopTenFilms(0, 0) = Range("A3")
TopTenFilms(0, 1) = Range("B3")
TopTenFilms(0, 2) = Range("C3")
TopTenFilms(0, 3) = Range("D3")
TopTenFilms(0, 4) = Range("E3")
End Sub
*How to loop over Multidimensional array*
Dim TopTenFilms(0 To 9, 0 To 4) As Variant
Dim Dimension1 As Long, Dimension2 As Long
For Dimension1 = 0 To 9
For Dimension2 = 0 To 4
TopTenFilms(Dimension1, Dimension2) = Range("A3").Offset _
(Dimension1, Dimension2).Value
Next Dimension2
Next Dimension1
*It is good practice to use upperbound and lowerbound
UBound And LBound)*
*Syntax For lbound and ubound for multidimensional array*
Dim TopTenFilms(0 To 9, 0 To 4) As Variant
Dim Dimension1 As Long, Dimension2 As Long
For Dimension1 = LBound(TopTenFilms, 1) To UBound(TopTenFilms, 1)
For Dimension2 = LBound(TopTenFilms, 2) To UBound(TopTenFilms, 2)
TopTenFilms(Dimension1, Dimension2) = Range("A3").Offset _
(Dimension1, Dimension2).Value
Next Dimension2
Next Dimension1
*What are static arrays*
when we have a fixed number of elements in each direction so theyre
referred as fixed size or static arrays
*What are dynamic arrays*
if you dont know how large the array needs to be like for example you cant
predict how many rows you will have etc.
*Syntax for dynamic arrays*
Dim TopTenFilm() As Variant
Dim D1 As Long, D2 As Long
D1 = Range("A3", Range("A3").End(xlDown)).Cells.Count - 1
D2 = Range("A3", Range("A3").End(xlToRight)).Cells.Count - 1
ReDim TopTenFilm(0 To D1, 0 To D2)
*Quicker Way to Dynamic Multidimension Array and how to populate it*
Sub QuickWayDynamicArray()
Dim TopFilms() As Variant
TopFilms = Range("A3", Range("A3").End(xlDown).End(xlToRight)).Value
Worksheets.Add
Range(ActiveCell, ActiveCell.Offset(UBound(TopFilms, 1) - 1, UBound(TopFilms,
2) - 1)).Value = TopFilms
Erase TopFilms
End Sub
___________________________________________________________________________
CHARTS
*How to add charts*
Charts.add in vba
*How to delete charts in all workbook?*
Application.DisplayAlerts = False
On Error Resume Next
Charts.delete
*If you select a single cells, the chart will be based on the entire region*
*How to select non contiguous column to create chart?*
Worksheets("Awards 2015").Activate
Union(Range("A3", Range("A3").End(xlDown)), Range("C3",
Range("C3").End(xlDown))).Select
Charts.Add
*How to declare variable to loop over a range?*
Dim Films As Range, Film As Range, ChartCells As Range
Set Films = Range("A3", Range("A3").End(xlDown))
Set ChartCells = Range("A3", Range("A3").End(xlToRight))
For Each Film In Films
If Film.Offset(0, 2).Value >= 1 Then
Set ChartCells = Union(ChartCells, Range(Film, Film.End(xlToRight)))
End If
Next Film
ChartCells.Select
Charts.Add
*Referencing a Chart*
dim ch as Chart
worksheets("Shee1").select
Range("A3:C19").select
set ch = Charts.add
*How to change chart type and modify it*
dim ch as Chart
worksheets("Shee1").select
Range("A3:C19").select
set ch = Charts.add
ch.chartType = xl3dpie
ch.HasLegend = true
ch.Hastitle = true
ch.ChartTitle.Text = "Noms vs. Wins"
*How to insert axis title*
dim ch as Chart
worksheets("Shee1").select
Range("A3:C19").select
set ch = Charts.add
ch.axes(xlcategory).HasTitle = true
ch.axes(xlcategory).AxisTitle.Text = "Film Name"
ch.axes(xlvalue).HasTitle = true
ch.axes(xlvalue).AxisTitle.Text = "Quantity"
*How to add data labels*
dim ch as Chart
worksheets("Shee1").select
Range("A3:C19").select
set ch = Charts.add
ch.seriescollection(1).hasdatacollections = true
ch.seriescollection(2).hasdatacollections = true
*how to add data labels when there is too many*
dim s as series
dim ch as Chart
worksheets("Shee1").select
Range("A3:C19").select
set ch = Charts.add
for each s in ch.seriescollection
s.hasdatalabels = true
next s
https://www.youtube.com/playlist?list=PLGs61FH9ETZPGqw-RIwteTlfsPPpOp-qP