如果我不知道名字,是否可以查看工作表上是否存在按钮?
我在“ThisWorkbook”中有代码,在打开工作簿时会创建一个按钮。但是,如果按钮已经存在,我不希望它创建一个按钮。所以我需要一种方法来检测按钮是否存在。
我还有另一种方法可以解决这个问题,我只会因为这一点而包括在内!
单击该按钮会创建一个名为“Transpose Data”的新工作表。因此,如果按钮在那里,该工作表也在那里。所以我尝试了以下子目录:
Private Sub Workbook_Open()
Dim btn As Button
Dim rng As Range
On Error GoTo Errorhandler
Sheets("Transposed Data").Activate
Errorhandler:
MsgBox ("ERROR")
With Worksheets("Program Sheet")
Set rng = .Range("A4:C4")
Set btn = .Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
With btn
.Caption = "Click here to continue"
.AutoSize = True
.OnAction = "TableCreation"
End With
End With
End Sub
我认为这段代码只有在发现转置数据工作表不存在时才会创建按钮,这正是我想要的。但是,此代码只是表示每次尝试运行它时都会出错。我已经单独测试了所有部件,但它们都有效,所以我不确定问题是什么。
但是,如果有一种不同的方法来检测按钮是否已经存在于工作表中,我不需要这样,因为我可以简单地创建一个if / then语句!
答案 0 :(得分:1)
我可以看到两种方法:
1)检查按钮是否已存在(假设只有一个按钮)
Private Sub Workbook_Open()
Dim btn As Button, rng As Range
With Worksheets("Program Sheet")
If .Shapes.Count = 0 Then //i.e. there aren't any buttons...
Set rng = .Range("A4:C4")
Set btn = .Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
With btn
.Caption = "Click here to continue"
.AutoSize = True
.OnAction = "TableCreation"
End With
End If
End With
End Sub
2)检查工作表Transposed Data
是否已存在
Private Sub Workbook_Open1()
Dim btn As Button, rng As Range, sht As Worksheet
On Error Resume Next
Set sht = Sheets("Transposed Data")
If sht Is Nothing Then //i.e. there is not worksheet called "Transposed Data"
With Worksheets("Program Sheet")
Set rng = .Range("A4:C4")
Set btn = .Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
With btn
.Caption = "Click here to continue"
.AutoSize = True
.OnAction = "TableCreation"
End With
End With
End If
End Sub