在VBA中,我有一个组合框代码,它将添加新的格式化工作表。我的问题是输入现有工作表名称时出错。如果用户输入了工作表的现有名称,我需要一个代码来显示msgbox“工作表名称已使用”。
这是我的代码。
Private Sub combobox1_KeyDown(ByVal KeyCode As_ MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
Dim wrksht1 As Worksheet, a As String
a = ComboBox1.Value
Set wrksht1 = ActiveWorkbook.Worksheets("FORMAT")
Sheets.ADD after:= Sheets(Sheets.Count)
ActiveSheet.Name = a
wrksht1.Cells.Copy
With ActiveWorkbook.Sheets(a).Cells
.PasteSpecial Paste:=xlPasteAll
Application.CutCopyMode = False
End With
End Sub
答案 0 :(得分:0)
您可以使用助手功能:
Function IsSheetAlreadyThere(shtName As String)
On Error Resume Next
IsSheetAlreadyThere = Not Sheets(shtName) Is Nothing
End Function
并在您的子网站中利用它:
Private Sub combobox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
Dim a As String
a = ComboBox1.Value
If IsSheetAlreadyThere(a) Then
MsgBox a & "is the name of an already existing sheet"
Else
Dim wrksht1 As Worksheet
Set wrksht1 = ActiveWorkbook.Worksheets("FORMAT")
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = a
wrksht1.Cells.Copy
With ActiveWorkbook.Sheets(a).Cells
.PasteSpecial Paste:=xlPasteAll
Application.CutCopyMode = False
End With
End If
End If
End Sub