如何修复'运行时错误'1004'PasteSpecial

时间:2019-09-07 05:18:56

标签: excel vba

我有一个文件(称为原始文件),该文件的每一行都有部分信息。每行都有一个文件名列(将从中捕获信息)。

对于每一行,我想在“文件名”列中打开文件,并从某些行中获取信息。

在文件中只有一列,行为“ Supplier Number:_____”,此行的位置是可变的,因此我想遍历文件中的每一行以复制此单元格值并将其粘贴放入相应行的原始文件中。

这是我到目前为止所拥有的:

Const FOLDER_PATH = "C:\Users\[user]\Downloads\"

Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet
    Dim source As String
    Dim target As String
    Dim update As String
    Dim rowT As Integer

    rowT = 2
    rowTT = 1

    Dim rowRange As Range
    Dim colRange As Range
    Dim rowRangeT As Range

    Dim LastCol As Long
    Dim LastRow As Long
    Dim LastRowT As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A2:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        source = FOLDER_PATH & wks.Cells(i, 18).Value 'the name of the file we want to grab info from in this Column, always populated

        'if the cell is empty, search through the file for "Supplier Number : "
        If IsEmpty(wks.Cells(rowT, 19)) Then
            Set wb = Workbooks.Open(source)
            wb.Activate
            LastRowT = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
            Set rowRangeT = wks.Range("A1:A" & LastRowT)
            For Each i In rowRangeT
                If InStr(i.Cells.Offset(rowTT), "Supplier") > 0 Then
                     Range("A" & rowTT).Select
                     Selection.Copy
                     Windows("Get Supplier Number.xlsm").Activate
                     Range("A" & rowT).Select
                     wks.Paste
                Else
                    rowTT = rowTT + 1
                End If
            Next i

            wb.Close


    Next rrow
    ScreenUpdating = True
End Sub

我收到粘贴特殊错误1004。

可以预料的是,对于“获取供应商编号.xlsm”中的每一行,该行的A列将使用信息进行更新

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

首先,您应该摆脱ActivateSelect方法。您不必使用它们,它们不会为您的代码提供任何帮助。使用它们不是一个好方法。

为避免它们,您应该使用特定的引用。您正在执行的操作,直到确定为止。在for循环内,设置wb后,将所有内容替换为以下内容:

With wb.Worksheets(1)
    LastRowT = .Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
    Set rowRangeT = .Range("A1:A" & LastRowT)
    For Each i In rowRangeT
        If InStr(i.Cells.Offset(rowTT), "Supplier") > 0 Then
             .Range("A" & rowTT).Copy wks.Range("A" & rowT)
        Else
            rowTT = rowTT + 1
        End If
    Next i
    wb.Close
End With

我认为这应该为您完成工作。

PS:如果只需要打开的工作簿中单元格的值,则可以用简单的等式替换Copy行:

wks.Range("A" & rowT) = .Range("A" & rowTT)