excelvbakeyboard-eventsworksheetautorun

How to autorun a macro after opening a workbook?


I have managed to create a simple macro: When the cell B1 is active and an Enter key is pressed, the active cell is changed to the cell B4.

This is Module2:

Sub B1ToB4()
    Range("B4").Select
End Sub

This is Sheet1 under Microsoft Excel Objects:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If ActiveCell.Address = "$B$1" Then
        Application.OnKey "{ENTER}", "B1ToB4"
        Application.OnKey "~", "B1ToB4"
    Else
        Application.OnKey "{ENTER}"
        Application.OnKey "~"
    End If
End Sub

This is in ThisWorkbook, so that whenever I open the workbook, the cell B1 is selected.

Private Sub Workbook_Open()
    Range("B1").Select
End Sub

The problem I'd like to solve is that when I open the workbook and press Enter, the macro does not work and the active cell is changed to the B2, not B4. The problem may come from using the Worksheet_SelectionChange event which requires making some change in the worksheet in order to activate the macro. After doing some change, the macro starts to work. I'd like the macro to work right after opening the workbook without making any changes in it, so I'd appreciate some help. I've checked similar topics here, but I just don't know what to change in my case.


Solution

  • Insert this line in Workbook_Open

    Private Sub Workbook_Open()
        Range("B1").Select
        set dummy = Range("B1")
        Sheet1.Worksheet_SelectionChange (dummy)
    End Sub
    

    and declare as Public Sub Worksheet_SelectionChange