Automatically Run an Excel Macro

Auto run macro excel… Do you want to run an excel macros automatically when the file is open or close?

Microsoft Excel provide us the opportunity to run a macro automatically every time we open or close the excel workbook file, using the event Workbook_Open and Workbook_BeforeClose.

In the Microsoft Visual Basic Editor page, in the ThisWorkbook module, we simply create two new sub procedure called Workbook_Open and Workbook_BeforeClose. In both sub procedure, we call the method that we want to run automatically when the workbook is open or closed.

Private Sub Workbook_Open ()

    Call onFileOpenMacro

End Sub
Private Sub Workbook_BeforeClose (Cancel As Boolean)

    Call onFileCloseMacro

End Sub

In this example, when the workbook is opened, we will automatically run macros called onFileOpenMacro, we also automatically run macros called onFileCloseMacro just before the excel workbook is closed.

Posted in Workbook and Worksheet | Tagged , , , | 18 Comments

Excel VBA Looping Tutorial

Do while … loop, do until … loop, do … loop while, do … loop until, and while … wend are the format of looping that we can use in Excel VBA.

The main reason why we need to perform looping is to simplified a repeating tasks. Rather then manually calling a block of code over and over again, it’s more simple and readable if we make it into loop.

There are two kind of loop

First, looping as long as the condition is true or false. This type of loop check the value of condition first, before the looping begin to start.

Second, repeat the task until the condition achieved. This type of loop will check the value of condition when the looping is finish.

Which one that we gonna pick is depend on our condition or purpose.

Syntax

Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]

Loop

Or

Do
[statements]
[Exit Do]
[statements]

Loop [{While | Until} condition]

And

While condition
[statements]

Wend

While … wend is the same with do while … loop, and do while … loop is more structured and flexible compare to while … wend statement.

Examples:

' example of do while ... loop
Sub ChkFirstWhile()
    counter = 0
    myNum = 20
    ' do while myNum > 10
    ' we perform condition check before we do loop
    ' if the first check fail to meet the criteria
    ' no loop will be perform
    Do While myNum > 10
        myNum = myNum - 1
        counter = counter + 1
    Loop
    MsgBox "The loop made " & counter & " repetitions."
End Sub

' example of do ... loop while
Sub ChkLastWhile()
    counter = 0
    myNum = 9
    ' do ... loop while myNum > 10
    ' we perform condition check after the loop
    ' we do at least 1 loop
    Do
        myNum = myNum - 1
        counter = counter + 1
    Loop While myNum > 10
    MsgBox "The loop made " & counter & " repetitions."
End Sub

' example of do until ... loop
' the principle is the same with do while ... loop
Sub ChkFirstUntil()
    counter = 0
    myNum = 20
    Do Until myNum = 10
        myNum = myNum - 1
        counter = counter + 1
    Loop
    MsgBox "The loop made " & counter & " repetitions."
End Sub

' example of do ... loop until
' the principle is the same with do ... loop while
Sub ChkLastUntil()
    counter = 0
    myNum = 1
    Do
        myNum = myNum + 1
        counter = counter + 1
    Loop Until myNum = 10
    MsgBox "The loop made " & counter & " repetitions."
End Sub

' example of while ... wend loop
Sub ChkWhile()
    Dim Counter
    Counter = 0    ' Initialize variable.
    While Counter < 20    ' Test value of Counter.
        Counter = Counter + 1    ' Increment Counter.
    Wend    ' End While loop when Counter > 19.
    Debug.Print Counter    ' Prints 20 in the Immediate window.
End Sub

FIN.

Posted in Excel Tutorial | Tagged , , , , , , , , , | 10 Comments

Convert Excel Column Number into Column Name

Update:

Sorter version of the VBA function:

Function Number2Char(c As Integer) As String
   Number2Char = Split(Cells(1, c).Address, "$")(1)
End Function

Courtesy of The Plaid Cow.

OR

Function Number2Char(ByVal vNumber)

    Dim addr As String
    If vNumber  256 Then Exit Function

    addr = Range("A1").Offset(0, vNumber - 1).Address
    Number2Char = Replace(Replace(addr, "$", ""), Range(addr).Row, "")

End Function

Courtesy of Stan Scott.

Original post:

Converting Excel column number into column name, for example 1 into A or 52 into AZ, is needed occasionally, and the following function will do the convertion for us.

Function Number2Char(ByVal vNumber)
    Dim iDiv As Double, iMod As Integer
    If vNumber < 1 Then Exit Function

    iDiv = vNumber
    While iDiv > 26
        iMod = iDiv Mod 26
        If iMod = 0 Then
            iMod = 26
            iDiv = iDiv - 1
        End If
        Number2Char = Chr(64 + iMod) & Number2Char
        iDiv = iDiv \ 26
    Wend

    Number2Char = Chr(64 + iDiv) & Number2Char
End Function

Use this function as formula in the Excel formula bar, ex: =NUMBER2CHAR(52)

FIN.

Posted in Workbook and Worksheet | Tagged , , , , , , , , , , , | 18 Comments

Check If Excel Workbook is Already Open or Not

In my case, I work a lot with transferring data from current Excel Workbook to another Excel Workbook, and to be able to do that, of course I need to make sure whether the destination Workbook is already open or not.

The following excel vba function assigned to check whether a workbook we need is open or not.

Using Workbook name as an input parameter, the function will do a looping in Workbooks collection to check all opened Workbook name, if there is a Workbook with the same name with the Workbook that we looking for, then the function will return true, and false if otherwise.

Public Function CheckSourceAvailability(sWorkBook As String) _
  As Boolean
    Dim wb As Workbook, bResult As Boolean
    bResult = False
    For Each wb In Application.Workbooks
        If InStr(LCase(wb.Name), LCase(sWorkBook)) > 0 Then
            bResult = True
            Exit For
        End If
    Next wb
    CheckSourceAvailability = bResult
End Function

All information about opened Workbook was saved by Excel in a collection object called Workbooks, just like Worksheets collection used by Excel to save information about all the Worksheets available.

FIN.

Posted in Cells and Range | Tagged , | 11 Comments

How To Find Row Position of a Particular Text

Sometimes in Excel, we need to find the row position of a particular text, maybe to be able to paste certain of data right below the corresponding text or else.

Very useful if we have an Excel Worksheet Template that we use a lot, with fix header on it.

' Input param: Text we want to look for
' Optional input params:
'     Search direction (forward, backward),
'     Search order (in row or column)
' Output: row position of the text being searched

Private Function pFindRowPos(sText As Variant, _
  Optional SearchDirection As XlSearchDirection = xlNext, _
  Optional SearchOrder As XlSearchOrder = xlByRows) As Long

    Dim lResult As Long, oRg As Range

    Set oRg = Cells.Find(What:=sText, LookIn:=xlValues, _
    LookAt:=xlPart, SearchOrder:=SearchOrder, _
                 SearchDirection:=SearchDirection, _
    MatchCase:=False, SearchFormat:=False)

    If Not oRg Is Nothing Then lResult = oRg.Row

    pFindRowPos = lResult

    Set oRg = Nothing

End Function

FIN.

Posted in Cells and Range | Tagged , , , , , , , , , , , , , | 14 Comments

Select All Cells With Formula In It

Let say we want to distinguish between ordinary cells and cells with formula in it, so we give a special background color to the cells with formula.

For doing it manually is time consuming, especially on Excel Worksheet with large of cells with formula in it (usually a very complex worksheet).

The following vba macro code will do the trick for us.

Sub SelectAllCellsWithFormula()

    'select all cell with formula
    Cells.SpecialCells(xlCellTypeFormulas).Select

    'change cell background color
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.399975585192419
        .PatternTintAndShade = 0
    End With

End Sub

FIN

Posted in Cells and Range | Tagged , , , | 6 Comments

Move Cursor To One Cell Below Last Row With Data

Ever want to paste some data into new empty cell after the last cell with data in certain column? Then take a look at this simple macro.

    'first, select cell in the first row of that column, like A1, K1, etc
    Range("A1").Select

    'move to the last cell with data
    Selection.End(xlDown).Select

    'move to one row below it
    ActiveCell.Offset(1, 0).Select

    'paste the copied data in there
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

Simple isn’t it? Simple code, but will help us a lot each time we wanna move the active cell into one cell below the last cell contained any kind of data, in the same column.

One requirement needed to use this simple excel vba macro, first we need to select the first cell in the same column where we wanna do the selection.

Posted in Excel VBA Function | Tagged , , , , , , , , , , , | 19 Comments