Super Important Tools and Excel Logic

Determining the Last Row in your Data Set
the macro below displays the last row in the specified column
    Sub lastRowCode()
        lastRow = Cells(Rows.Count, <specified column>).End(xlUp).Row
        MsgBox lastRow
    End Sub
    
Top

Index

Determining the Last Column in your Data Set
the macro below displays the last column in the specified row
    Sub lastColumnCode()
        lastColumn = Cells(<specified row>, Column.Count).End(xlToLeft).Column
        MsgBox lastColumn
    End Sub
    
Top

Index

Determining the Next Row in your Data Set
the macro below displays the next row in the specified column
    Sub nextRowCode()
        nextRow = Cells(Row.Count, <specified column>).End(xlUp).Row + 1
        MsgBox nextRow
    End Sub
    
Top

Index

Recording a Macro
on Developer tab click 'Record Macro'
a dialog apperas which creates a module
use tools to perform desired actions
when done click 'Stop Recording'
the macro is record in the module
Top

Index

Dynamic Sorting
the recorded macro below shows how to sort using multiple columns
column B is sorted then column A is sorted relative to column B
    Sub Macro1()
        Range("A9").Select
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B2:B9"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A2:A9"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SetRange Range("A1:B9")
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        ActiveWorkbook.Save
    End Sub
    
the macro below sorts dynamically
    Sub dynamicSorting()
        Range("A1").Select

        lastRow = ThisWorkbook.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
        ' use the last row variable to dynamically set the range
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B2:B" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A2:A9"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Sheet1").Sort
        ' use the last row variable to dynamically set the range
            .SetRange Range("A1:B" & lastRow)
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        ActiveWorkbook.Save
    End Sub
    
Top

Index

Absolute vs Relative References
absolute reference always starts from a defined point
    Sub absolute()
        Range("B4").Select
        ActiveCell.FormulaR1C1 = "hello there"
        Range("C5").Select
    End Sub
    
relative reference starts from the selected cell
    Sub relative()
        ActiveCell.Offset(3, 1).Select
        ActiveCell.FormulaR1C1 = "hello there"
        ActiveCell.Offset(1, 1).Select
    End Sub
    
Top

Index

Using With and End With
the two macros below do the same thing
    Sub withoutWith()
        Range("C6").Value = 12
        Range("C6").Font.Bold = True
        Range("C6").Font.Italic = True
    End Sub
    
    Sub withWith()
        With Range("C6")
            .Value = 12
            .Font.Bold = True
            .Font.Italic = True
        End With
    End Sub
    
Top

Index

Comparison Operators in Excel VBA
Operator Action
= equals
<> not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Top

Index

If Then Statement
    Sub ifStatement()
        If Range("C6") = 12 Then
            MsgBox "C6 is equal to 12"
        End If
    End Sub
    
Top

Index

Using Is Not Equal To (<>)
    Sub ifStatement()
        If Range("C6") <> 12 Then
            MsgBox "C6 is not equal to 12"
        End If
    End Sub
    
Top

Index

Logical Operator, NOT
     Sub ifStatement()
        If Not Range("C6") = 12 Then
            MsgBox "C6 is not equal to 12"
        End If
    End Sub
    
    
Top

Index

If, Then, Else Statement
    Sub ifElseStatement()
        If Range("C6") = 12 Then
            MsgBox "C6 is equal to 12"
        Else
            MsgBox "C6 is not equal to 12"
        End If
    End Sub
        
Top

Index

If, Then, ElseIf Statement
    Sub ifElseStatement()
        If Range("C6") = 12 Then
            MsgBox "C6 is equal to 12"
        ElseIf Range("C6") > 12 Then
            MsgBox "C6 is greater than 12"
        ElseIf Range("C6") < 12 Then
            MsgBox "C6 is less than 12"
        End If
    End Sub
        
Top

Index

Comparative Operators with Text and Numbers
    Sub ifElseStatement()
        If Range("C6") = 12 Then
            MsgBox "C6 is equal to 12"
        ElseIf Range("C6") > 12 And IsNumeric(Range("C6")) Then
            MsgBox "C6 is greater than 12"
        ElseIf Range("C6") < 12 And IsNumeric(Range("C6")) Then
            MsgBox "C6 is less than 12"
        Else
            MsgBox "Please enter a number into C6."
        End If
    End Sub
            
Top

Index

Using If Then Statements in a One-Liner of Code
a single line If statement does not require a closing 'End If"
    Sub singleLineIf()
        If Range("C6") = 12 Then MsgBox "C6 is equal to 12"
    End Sub
    
Top

Index

Using GOTO and Labels
    Sub gotoExample()
        Goto myLabel
        ' code to be skipped
        ' colon in next line ids a label
        myLabel:
    End Sub
    
Top

Index

Select Case as Alternative to If Then Statements
    Sub mySwitch()
        Select Case Range("C6")
            Case 12
                MsgBox "12"
            Case Is < 2 And IsNumeric(Range("C6"))
                MsgBox "less that 2"
            Case Else
                MsgBox "else"
        End Select
    End Sub
Top

Index

Message Box with Yes and No Buttons
    Sub myMsgBox()
    start:
        answer = MsgBox("Do you like excel VBA?", vbYesNo)
        If answer = vbYes Then
            MsgBox "yes"
        ElseIf answer = vbNo Then
            MsgBox "no"
            GoTo start
        End If
    End Sub
    
Top

Index

Relative Positioning using Offset
Offset(<row>, <column>)
    Sub offsetSub()
        Selection.Offset(3, 1) = Selection
        Cells(1, 1).Offset(4, 1) = "offset by 4,1"
        Range("E4").Offset(-3, -3) = "offset by -3,-3"
    End Sub
    
Top

Index

User Defined Functions 101
the function below is used in the spreadsheet example shown further below
the return value has the same name as the function
    Function KGrams(lbs)
        KGrams = lbs * 0.453592
    End Function
    
to calculate the kilograms for a cell call the function using the desired pounds cell as an arg as shown in the sixth row

  A B
1 Pounds =KGrams()
2 1 0.453592
3 13 5.986696
4 40 18.14368
5 20.25 9.185238
6 23 =KGrams(A6)
Top

Index

UDF Lesson 2
the function below has an added optional arg
optional arg is the number of decimal places to return
    Function KGrams(lbs, Optional dplaces)
        If IsMissing(dplaces) Then
            KGrams = lbs * 0.453592
        Else
            KGrams = Round(lbs * 0.453592, dplaces)
        End If
    End Function
    
cell and number of decimal places as args as shown in the sixth row

  A B
1 Pounds =KGrams()
2 1 0.45
3 13 5.99
4 40 18.14
5 20.25 9.19
6 23 =KGrams(A6, 2)
Top

Index

Exercise 6a
the macro below has a bug
when it runs it is supposed to clear all the data rows and leave the header
if there are no data rows the header gets cleared
    Sub Exercise6A()
        'get last row
        lastRow = Cells(Rows.Count, 1).Row
        'clear last report
        Range("A2:b" & lastRow).ClearContents

        Range("a2") = "1"
        Range("b2") = "Name1"

        Range("a3") = "2"
        Range("b3") = "Name2"

        Range("a4") = "3"
        Range("b4") = "Name3"
    End Sub
    
resolve problem using conditional
    ...
    If lastRow > 1 Then
        'clear last report
        Range("A2:b" & lastRow).ClearContents
   End If
   ...
Top

Index

Exercise 6b
    Sub exercise6b()
        selectedRow = Selection.Row
        lastRow = Cells(Rows.Count, 4).End(xlUp).Row
        If selectedRow <= lastRow And selectedRow > 1 Then
            answer = MsgBox("Add $100 to current row sales?", vbYesNo)
            If answer = vbYes Then
                sales = Cells(selectedRow, 4).Value
                Cells(selectedRow, 4).Value = sales + 100
            End If
        End If
    End Sub
    
Top

Index

n4jvp.com