设置对工作表的引用会生成错误:对象'_Worksheet'的方法'名称'

问题描述 投票:0回答:2

我的宏正在浏览一个文件夹并选中每个Excel文件并删除名为some_Accounts的第一个选项卡,然后将粘贴数据复制到工作表名称匹配的主工作簿。

获取以下错误在以下代码行中对象'_Worksheet'的方法'Name'

Set wsDst = wbDst.Worksheets(wsSrc.Name)

我确保工作表名称相同。

Sub ProjectMacro()
Dim wbDst As Workbook
Dim wsDst As Worksheet
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String
Dim lLastRow As Long
Dim LC As Long
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False

Set wbDst = ThisWorkbook
MyPath = "C:\Users\Adam\Desktop\some files\"
strFilename = Dir(MyPath & "*.xls*", vbNormal)

Do While strFilename <> ""

    Set wbSrc = Workbooks.Open(MyPath & strFilename)

    'loop through each worksheet in the source file
    For Each wsSrc In wbSrc.Worksheets
        'Find the corresponding worksheet in the destination with the same 
        name as the source

        For i = K To 1 Step -1
            t = Sheets(i).Name
            If t = "some_Accounts" Then
                Application.DisplayAlerts = False
                Sheets(i).Delete
                Application.DisplayAlerts = True
            End If
        Next i

        Set wsDst = wbDst.Worksheets(wsSrc.Name)

        On Error GoTo 0

        If wsDst.Name = wsSrc.Name Then
            lLastRow = wsDst.UsedRange.Rows(wsDst.UsedRange.Rows.Count).Row + 1
            wsSrc.UsedRange.Copy
            wsDst.Range("A" & lLastRow).PasteSpecial xlPasteValues
        End If
    Next wsSrc

    wbSrc.Close False
    strFilename = Dir()
Loop

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
excel vba
2个回答
1
投票

现在,你正在Worksheets的所有wbSrc循环。当wsSrc是“some_Accounts”表时,在For i = K to 1... End For中删除它后,它就不再存在,因此wsSrc没有Name并且稍后会抛出错误。如果要删除工作表,请在遍历工作簿中的所有工作表之前执行此操作。

但是,由于您在不保存更改的情况下关闭wbSrc,我认为您不需要删除该表;你可以在循环时跳过它。

这看起来像这样:

For Each wsSrc In wbSrc.Worksheets
    If wsSrc.Name <> "some_Accounts" Then
    '... copy and pasting code here
    End If
Next wsSrc

请注意,您可以在代码中加入WorksheetExists函数,以确保wbDst中有匹配的工作表。这已经在另一个答案中提供了。


1
投票

尝试将其放入代码中以查看工作表是否存在:

If worksheetExists(wbDst, wsDst.Name) = true then
  MsgBox "Exists!"
else
  MsgBox "Does not exist!"
end if

   Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean

    On Error Resume Next
    worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
    Err.Clear: On Error GoTo 0

   End Function
© www.soinside.com 2019 - 2024. All rights reserved.