简体   繁体   中英

Excel - How to create button upon Workbook_Open event

I'm trying to make an Excel Add-In to create a simple button when any workbook is opened, but I'm getting

Object variable or With Block variable not set

I think this is happening because technically there is no 'ActiveWorkbook' yet.

First thing I want to do is delete any buttons currently on the sheet. Then I want to place a button.

Anyone know how to make that happen?

Code

Private Sub Workbook_Open()
    ActiveWorkbook.ActiveSheet.Buttons.Delete
    Dim CommandButton As Button
    Set CommandButton = ActiveWorkbook.ActiveSheet.Buttons.Add(1200, 100, 200, 75)
    With CommandButton
        .OnAction = "Test_Press"
        .Caption = "Press for Test"
        .Name = "Test"
    End With
End Sub

I then have a Private Sub Test_Press() to display a MsgBox. The button is not being created though.

Credit goes to http://www.jkp-ads.com/Articles/FixLinks2UDF.asp

Note: I have another module I didn't post below, which houses the macro Project_Count I tied to the button I place on the workbook only if the workbook name is TT_GO_ExceptionReport

I also have a VBScript that downloads the Add-In, places it in the users addin folder, and installs it. If you want to know how to do that, leave a comment.

Code of Add-In that solved the problem:

ThisWorkbook

Option Explicit
    Private Sub Workbook_Open()
    ' Purpose   : Code run at opening of workbook
    '-------------------------------------------------------------------------    
    'Initialise the application
    InitApp
    modProcessWBOpen.TimesLooped = 0

    Application.OnTime Now + TimeValue("00:00:03"), "CheckIfBookOpened"
End Sub

Module 1 named modInit Option Explicit

'Create a module level object variable that will keep the instance of the
'event listener in memory (and hence alive)
Dim moAppEventHandler As cAppEvents

    Sub InitApp()
        'Create a new instance of cAppEvents class
        Set moAppEventHandler = New cAppEvents
        With moAppEventHandler
            'Tell it to listen to Excel's events
            Set .App = Application
        End With
    End Sub

Module 2 named modProcessWBOpen Option Explicit

'Counter to keep track of how many workbooks are open
Dim mlBookCount As Long

'Counter to check how many times we've looped
Private mlTimesLooped As Long

' Purpose   : When a new workbook is opened, this sub will be run.
' Called from: clsAppEvents.App_Workbook_Open and ThisWorkbook.Workbook_Open
'-------------------------------------------------------------------------
Sub ProcessNewBookOpened(oBk As Workbook)

    If oBk Is Nothing Then Exit Sub
    If oBk Is ThisWorkbook Then Exit Sub
    If oBk.IsInplace Then Exit Sub

    CountBooks

    'This checks to make sure the name of the new book matches what I 
    'want to place the button on
    If oBk.Name = "TT_GO_ExceptionReport.xlsm" Then
        Dim CommandButton As Button
        Set CommandButton = Workbooks("TT_GO_ExceptionReport.xlsm").Sheets(1).Buttons.Add(1200, 100, 200, 75)
        With CommandButton
            .OnAction = "Project_Count"
            .Caption = "Press for Simplified Overview"
            .Name = "Simplified Overview"
        End With
    End If
End Sub

Sub CountBooks()
    mlBookCount = Workbooks.Count
End Sub

Function BookAdded() As Boolean
    If mlBookCount <> Workbooks.Count Then
        BookAdded = True
        CountBooks
    End If
End Function

' Purpose   : Checks if a new workbook has been opened 
' (repeatedly until activeworkbook is not nothing)
'-------------------------------------------------------------------------
Sub CheckIfBookOpened()

    If BookAdded Then
        If ActiveWorkbook Is Nothing Then
            mlBookCount = 0
            TimesLooped = TimesLooped + 1
            'May be needed if Excel is opened from Internet explorer
            Application.Visible = True
            If TimesLooped < 20 Then
                Application.OnTime Now + TimeValue("00:00:01"), "CheckIfBookOpened"
            Else
                TimesLooped = 0
            End If
        Else
            ProcessNewBookOpened ActiveWorkbook
        End If
    End If
End Sub

Public Property Get TimesLooped() As Long
    TimesLooped = mlTimesLooped
End Property

Public Property Let TimesLooped(ByVal lTimesLooped As Long)
    mlTimesLooped = lTimesLooped
End Property

Class Module named cAppEvents

' Purpose   : Handles Excel Application events
'-------------------------------------------------------------------------
Option Explicit

'This object variable will hold the object who's events we want to respond to
Public WithEvents App As Application

Private Sub App_WorkbookOpen(ByVal Wb As Workbook)

    'Make sure newly opened book is valid
    ProcessNewBookOpened Wb
End Sub

Private Sub Class_Terminate()
    Set App = Nothing
End Sub

something like this?

Option Explicit
Sub Button()
    Dim cButton As Button
    Dim rng As Range
    Dim i As Long

    ActiveSheet.Buttons.Delete

    For i = 2 To 3 Step 2
        Set rng = ActiveSheet.Range(Cells(i, 2), Cells(i, 2))
        Set cButton = ActiveSheet.Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
        With cButton
            .OnAction = "Test_Press"
            .Caption = "Press for Test " & i
            .Name = "Test" & i
        End With
    Next i
End Sub

See Example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM