我有一个CommandButton,它打开一个UserForm并创建一个名为ComboBox Value的复制Sheet。
这是我的代码:
Private Sub CommandButton1_Click()
[UserForm1].Show ' Open UserForm
End Sub
Private Sub CommandButton2_Click()
Dim ws As Worksheet
ActiveWorkbook.Sheets("Sheet1").Visible = True ' Unhide Sheet
Sheets("Sheet1").Copy _
Before:=ActiveWorkbook.Sheets("Sheet1") ' Copy Sheet
Set ws = ActiveSheet
ws.Name = ComboBox1.Value ' Name Sheet
[UserForm1].Hide ' Close UserForm
ActiveWorkbook.Sheets("Sheet1").Visible = False ' Hide Sheet again
End sub
现在我的问题是,如果有两台名为“Machine Type 1”的机器,则Excel会出现错误。那么我需要在我的代码中进行哪些更改,第二张表将命名为例如“机器类型1(2)?
感谢您的帮助。
答案 0 :(得分:1)
你可以试试这个
Private Sub CommandButton1_Click()
If IsSheetThere(ComboBox1.Value) Then 'if some sheet with chosen name already there
Sheets(ComboBox1.Value).Copy Before:=Sheets(10) ' copy the existing sheet
With ActiveSheet 'reference just copied sheet
.UsedRange.Clear 'clear its content
Sheets("Sheet1").UsedRange.Copy ActiveSheet.Range("A1") ' copy Sheet1 content and paste into it
End With
Else 'otherwise
Sheets("Sheet1").Copy Before:=Sheets(Sheets.Count) ' make a copy of "Sheet1" sheet
ActiveSheet.Name = ComboBox1.Value 'and rename it as per chosen name
End If
Me.Hide
End Sub
Function IsSheetThere(shtName As String) As Boolean
On Error Resume Next
IsSheetThere = Not Sheets(shtName) Is Nothing
End Function
代码行:
Sheets(ComboBox1.Value).Copy Before:=Sheets(10) ' copy the existing sheet
让Excel承担以某种方式“计算”已使用所选名称的现有工作表数量的负担,并适当地命名新工作表
答案 1 :(得分:0)