简体   繁体   中英

VBA Excel Button Macro Error

I am programmatically placing a button on a worksheet and it places fine, however when I click it i get an error saying "Cannot run the macro. The macro may not be available in this workbook or all macros may be disabled". I believe I've set it up fine but here is my code if anyone spots anything would greatly appreciate it.

Sub ButtonGenerator()

    Application.ScreenUpdating = False

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    Dim lcolumncrc As Long
    lcolumncrc = CRC.LastColumnInCRC

    'Button Declarations
    Dim ShowHideDates As Button

    wsCRC.Buttons.Delete

    'Show/Hide Dates Button Set Up
    Dim SHDrange As Range

    Set SHDrange = wsCRC.Range(Cells(5, lcolumncrc + 2), Cells(5, lcolumncrc + 4))
    Set ShowHideDates = wsCRC.Buttons.Add(SHDrange.Left, SHDrange.Top, SHDrange.Width, SHDrange.Height)

    With ShowHideDates
        .OnAction = "wsCRC.SHDbtn"
        .Caption = "Show Hidden Date Columns"
        .Name = "ShowHideDates"
    End With

    Application.ScreenUpdating = True

End Sub

Sub SHDbtn()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")
    Dim ShowHideDates As Button

    Dim CurrentDateColumn As Long
    CurrentDateColumn = GetTodaysDateColumn()

    ActiveSheet.Unprotect

    If ShowHideDates.Caption = "Hide Old Date Columns" Then
        wsCRC.Range(wsCRC.Cells(5, 10), wsCRC.Cells(5, CurrentDateColumn - 6)).EntireColumn.Hidden = True
        ShowHideDates.Caption = "Show Hidden Date Columns"
    Else
        wsCRC.Range(wsCRC.Cells(5, 10), wsCRC.Cells(5, CurrentDateColumn - 6)).EntireColumn.Hidden = False
        ShowHideDates.Caption = "Hide Old Date Columns"
    End If

    ActiveSheet.Protect

End Sub

You're referring to a worksheet by the label you've given it within your code, not as a sheet itself.

Try changing:

.OnAction = "wsCRC.SHDbtn"

to

.OnAction = "CRC.SHDbtn"

or even

.OnAction = "SHDbtn"

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