我想在现有的excel文件中添加工作表调用“Master Record”。使用下面的代码,我可以创建工作表,但如果工作表已经退出,则创建具有不同名称Eg的工作表:Sheet2,Sheet3。
我不想创建任何其他工作表。它已经存在而不仅仅是反映消息。请告知我如何避免创建不必要的表格。
Dim Wb As Workbook
Dim ws As Worksheet
Set Wb = Workbooks.Open(TextBox2.Text)
Set ws = Wb.Sheets.Add
ws.Name = "Master Records"
Wb.Save
Wb.Close
答案 0 :(得分:0)
您需要检查它是否存在。
Dim exists as Boolean
Dim Wb As Workbook
Dim ws As Worksheet
Set Wb = Workbooks.Open(TextBox2.Text)
exists = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Master Records" Then
exists = True
End If
If exists = True Then 'Exit loop early if it finds that the sheet exists
Exit For
End If
Next i
If Not exists Then
Set ws = Wb.Sheets.Add
ws.Name = "Master Records"
Else
MsgBox("Sheet Exists")
End If