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

时间:2018-07-12 18:09:07

标签: excel vba

我的宏正在浏览一个文件夹,并选择每个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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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中有匹配的表。这已经在另一个答案中提供了。