简体   繁体   English

在外部工作簿中添加工作表

[英]Add Worksheet in external workbook

I want to add worksheet call "Master Record" in existing excel file. 我想在现有的excel文件中添加工作表调用“Master Record”。 With the below code, I am able to create the worksheet but if the worksheet is already exit, it is creating sheet with different name Eg: Sheet2, Sheet3. 使用下面的代码,我可以创建工作表,但如果工作表已经退出,则创建具有不同名称Eg的工作表:Sheet2,Sheet3。

I don't want to create any other sheets. 我不想创建任何其他工作表。 It it is already exist than just reflect message. 它已经存在而不仅仅是反映消息。 Please advise as to how can I avoid creating unnecessary sheet. 请告知我如何避免创建不必要的表格。

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

You need to check if it exists. 您需要检查它是否存在。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM