我在excel宏中有一个要求。这是场景:
我有2个工作簿,说A和B
工作簿“ A”包含工作表1,sheet2和sheet3,工作簿“ B”包含工作表4
现在我需要将工作簿“ B”与工作簿A进行比较。如果工作簿“ A”中存在工作表“ B”中没有的工作表(此处Sheet1,Sheet2,Sheet3),那么我需要将这3个工作表添加到工作簿“ B”
因此,最后,B工作簿应包含:工作表1,工作表2,工作表3和工作表4。
尝试以下代码,但无法正常工作。
Set act = ThisWorkbook
path = Sheet1.TextBox1.Text
Set owb = Workbooks.Open(Filename:=path)
For Each ws In ThisWorkbook.Worksheets
a = ws.Name
For Each ws1 In owb.Worksheets
If ws1.Name = a Then
MsgBox "Found"
Else
Set wsnew = owb.Sheets.Add
wsnew.Name = a
End If
Next ws1
Next ws
答案 0 :(得分:0)
您可以尝试为每个工作表设置一个引用,而不是检查每个工作表-如果设置了引用,则该表存在,如果抛出错误,则该表不存在。
我将使用一个单独的函数在现有工作表上返回TRUE / FALSE-这是我使用On Error Resume Next
忽略任何错误的几次。
Public Sub CopySheets()
Dim wrkBk As Workbook
Dim wrkSht As Worksheet
Dim wrkShtNew As Worksheet
Set wrkBk = Workbooks("Book2")
For Each wrkSht In ThisWorkbook.Worksheets
If Not WorkSheetExists(wrkSht.Name, wrkBk) Then
Set wrkShtNew = wrkBk.Worksheets.Add
wrkShtNew.Name = wrkSht.Name
Else
MsgBox wrkSht.Name & " exists.", vbOKOnly + vbInformation
End If
Next wrkSht
End Sub
Public Function WorkSheetExists(SheetName As String, Optional wrkBk As Workbook) As Boolean
Dim wrkSht As Worksheet
If wrkBk Is Nothing Then
Set wrkBk = ThisWorkbook
End If
On Error Resume Next
Set wrkSht = wrkBk.Worksheets(SheetName)
WorkSheetExists = (Err.Number = 0)
Set wrkSht = Nothing
On Error GoTo 0
End Function