Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workbook_Open sub won't run when I open the workbook?

Tags:

This program is supposed to create a button that the user can press to activate a different sub. From my searches online, it seems that the sub below should activate when opening up the workbook, but it's not?

What am I doing wrong?

Option Explicit
Private Sub Workbook_Open()
Dim btn As Button
Dim rng As Range
With Worksheets("Sheet1")
    Set rng = .Range("B2:C2")
        Set btn = .Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
    With btn
        .Caption = "To begin the program, please click this button"
        .AutoSize = True
        .OnAction = "TableCreation1"
    End With
End With
End Sub
like image 958
TheTreeMan Avatar asked Jul 06 '12 21:07

TheTreeMan


3 Answers

Make sure your Private Sub Workbook_Open() subroutine is pasted inside of the This Workbook object and not in a Module, Form, or Sheet object.

like image 54
danielpiestrak Avatar answered Oct 17 '22 10:10

danielpiestrak


Interesting. In 2009 a conflict with conditional formatting of the sheet to open is described, as in vbforum post.

It seems that this bug still exists in excel and prevents the workbook_open event from being fired. I have a workbook (old XLS-binary format) that simply does not fire the event in Excel 2003 and 2007 but does in 2013. I deleted all conditional formatting from the first worksheet but could still not get the workbook_open procedure to run in elder Excel-Versions.

A Workaround, I use in distributed workbooks is to use a local variable and a second event in the workbook as follows:

''
' private variable
Private wbOpenEventRun as Boolean

''
' procedure to be called by excel when workbook opens
Private Sub Workbook_Open()
    wbOpenEventRun = true
    ' perform tasks
End Sub

''
' the selection change event fires usually.
' performance is not reduced
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    If Not wbOpenEventRun Then Workbook_Open
    ' perform tasks in reaction of selection change events, if required
End Sub
like image 40
DrMarbuse Avatar answered Oct 17 '22 10:10

DrMarbuse


The solution I found was running the below code and then the "Open" event worked.

Sub EventRestore()

    Application.EnableEvents = True

End Sub
like image 35
Nazim Avatar answered Oct 17 '22 08:10

Nazim