Excel vba在工作簿中添加或删除工作表时,在主表中显示隐藏按钮。

问题描述 投票:1回答:1

我有一个带有简单宏的按钮,可以删除某些工作表.我想只在这些工作表实际存在的时候才显示这个按钮(我可以使用worksheets.count,因为我有2个 "永久 "的工作表;如果>2,那么我知道我有一个新的工作表,如果我想删除它,我想显示按钮)。

我想我必须使用 "Workbook.SheetChange事件",因为在这种情况下,"Worksheet.Change事件 "似乎对我不起作用。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim foglio_parametri As Worksheet
Set foglio_parametri = ThisWorkbook.Worksheets("PARAMETRI") 'my main sheet where I want to show/hide the button

Application.ScreenUpdating = True
If Application.Worksheets.Count > 2 Then
    foglio_parametri.CommandButton2.Visible = True
Else
    foglio_parametri.CommandButton2.Visible = False
End If


End Sub

非常感谢你的时间。

vba button
1个回答
1
投票

我不会使用你的名字,因为它们是用我不懂的外语写的。

让我们假设你所说的按钮是在一个名称为 sheet3 它还具有 代号 sheet3. 按钮本身的名称是 CommandButton1. 让我们进一步假设 一定 你说的单子上的名字 sheet4sheet5 然后,我将添加以下代码到 工作簿模块

Option Explicit

Private Sub Workbook_Open()
    Sheet3.HidecmdBtn
End Sub


Private Sub Workbook_SheetActivate(ByVal Sh As Object)
    If Sh.Name = "Sheet3" Then
        Sheet3.HidecmdBtn
    End If
End Sub

工作表模块sheet3 你有以下代码

Option Explicit

    Private Sub CommandButton1_Click()        
        ' Your code goes here

        ' In case your code deletes the sheets you have to hide the button
        HidecmdBtn
    End Sub

    Sub HidecmdBtn()

        Dim Sh As CommandButton
        ' My button is located on sheet 3 and has the name "CommandButton1"
        Set Sh = CommandButton1

        Dim sh1Name As String
        Dim sh2Name As String
        sh1Name = "Sheet4"
        sh2Name = "Sheet5"

        If SheetExists(sh1Name) Or SheetExists(sh2Name) Then
            Sh.Visible = msoTrue
        Else
            Sh.Visible = msoFalse
        End If    

    End Sub

在一个 正常模块 你有

Public Function SheetExists(SheetName As String, Optional wrkBook As Workbook) As Boolean

    If wrkBook Is Nothing Then
        Set wrkBook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
    End If

    Dim obj As Object

    On Error GoTo HandleError
    Set obj = wrkBook.Sheets(SheetName)
    SheetExists = True
    Exit Function

HandleError:
    SheetExists = False
End Function
© www.soinside.com 2019 - 2024. All rights reserved.