VBA调试代码,用于使用部分名称匹配在活动/打开的工作簿之间复制和粘贴

时间:2018-07-30 12:30:12

标签: excel vba excel-vba

我在这里的另一个线程中找到了此代码,但无法在我的书中正常使用... 我要实现的是...从名为“ SHIFT REPORT *”的wb调用该宏,该宏将查找并切换到名为“ PlayerTransactionReport *”的wb,以便在切换回SHIFT REPORT和粘贴。

我的代码是:

Sub Import_Data()

    Dim wb As Workbook
    Dim ShiftReport As Workbook
    Dim PlayerTransactionReport As Workbook

    Set ShiftReport = ThisWorkbook
    For Each wb In Workbooks
     If Left(wb.Name, 23) = "PlayerTransactionReport" Then Set PlayerTransactionReport = wb
    Next

    Sheets("Sheet1").Select
    Columns("A:Z").Select
    Selection.Copy

    Set PlayerTransactionReport = ThisWorkbook
    For Each wb In Workbooks
        If Left(wb.Name, 10) = "ShiftReport" Then Set ShiftReport = wb
    Next

    Sheets("Data").Select
    Range("A1").Select
    ActiveSheet.Paste

End Sub

当前,它不是将PlayerTransactionReport设置为活动wb,而是在我自己进行调试的整个过程中,我取得了不同程度的成功,但是我担心这可能在我之间,请帮忙!

谢谢,斯图尔特

2 个答案:

答案 0 :(得分:0)

每当引用Sheets()Columns()时,都必须参考上级工作表:

Sub Import_Data()

    Dim wb As Workbook
    Dim ShiftReport As Workbook
    Dim PlayerTransactionReport As Workbook

    Set ShiftReport = ThisWorkbook
    For Each wb In Workbooks
        If Left(wb.Name, 23) = "PlayerTransactionReport" Then Set PlayerTransactionReport = wb
    Next



    PlayerTransactionReport.Sheets("Sheet1").Select
    Columns("A:Z").Select
    Selection.Copy

    Set PlayerTransactionReport = ThisWorkbook
    For Each wb In Workbooks
        If Left(wb.Name, 10) = "ShiftReport" Then Set ShiftReport = wb
    Next

    PlayerTransactionReport.Sheets("Data").Select
    Range("A1").Select
    ActiveSheet.Paste

End Sub

如果您不参考父级工作表,那么将引用ActiveSheet或代码所在的表。

下一步,您可以改善以下2点:


If Not PlayerTransactionReport Is Nothing Then
    PlayerTransactionReport.Sheets("Sheet1").Select
    Columns("A:Z").Select
    Selection.Copy
End If

答案 1 :(得分:0)

Stop using Select and Activate

Sub Import_Data()

    Dim w As long
    Dim PlayerTransactionReport As Workbook, ShiftReport As Workbook

    Set ShiftReport = ThisWorkbook
    For w = 1 to Workbooks.count
        If Left(Workbooks(w).Name, 23) = "PlayerTransactionReport" Then
            Set PlayerTransactionReport = Workbooks(w)
            exit for
        end if
    Next w

    if w > Workbooks.count then
        debug.print "cannot find PlayerTransactionReport"
        exit sub
    end if

    PlayerTransactionReport.workSheets("Sheet1").Columns("A:Z").Copy _
      destination:=ShiftReport.workSheets("Data").Range("A1").

End Sub