有条件地将 Excel File-2 数据复制到 excel file-1?

Conditional copy Excel File-2 data to excel file-1?

我正在使用 Excel 2007。当某些列数据与文件匹配时,我尝试将单价从 Excel file-2 数据复制到 Excel file-1 -1 与文件 2.

感谢您的帮助和指导。

我的VBA代码:

子 mySales()
    Dim LastRow 为整数,i 为整数,erow 为整数,Pipe_Class 为字符串,Pipe_Description 为字符串,End_Type 为字符串,Pipe_Size 为字符串
    将 wbk 调暗为工作簿
    strPriceFile = "C:\Temp\File-2.xlsx"
    LastRow = ActiveSheet.Range(“A” & Rows.Count).End(xlUp).Row
    对于 i = 2 到最后一行
        Pipe_Class = ""
        Pipe_Description = ""
        End_Type = ""
        Pipe_Size = ""
        Pipe_Class = ActiveSheet.Cells(i, 1).Value
        Pipe_Description = ActiveSheet.Cells(i, 2).Value
        End_Type = ActiveSheet.Cells(i, 3).Value
        Pipe_Size = ActiveSheet.Cells(i, 4).Value
        设置 wbk = Workbooks.Open(strPriceFile)
        工作表("SOR2").Select
        如果单元格(i, 1) = Pipe_Class 并且单元格(i, 2) = Pipe_Description 并且单元格(i, 3) = End_Type 并且单元格(i, 4) = Pipe_Size 然后
            范围(单元格(i, 12), 单元格(i, 12)).Select
            Selection.Copy

???在这里之后如何 select 我当前的文件 & 粘贴 ?????????

            工作表("SOR1").Select
            erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).行
            ActiveSheet.Cells(erow, 12).Select
            ActiveSheet.Paste
            ActiveWorkbook.Save
        万一
    接下来我
    ActiveWorkbook.Close
    Application.CutCopyMode = 错误
结束子

我没有检查你的所有代码,但我重构了你问题中的内容,试图打开工作簿一次并分配适当的对象,以便你可以跟踪正在应用的操作哪个工作表。

Sub mySales() 
    Dim LastRow As Integer, i As Integer, erow As Integer
    Dim wbSrc As Workbook
    Dim wsSrc As Worksheet
    Dim wbDst As Workbook
    Dim wsDst As Worksheet
    Dim strPriceFile As String

    Set wbDst = ActiveWorkbook
    Set wsDst = ActiveSheet

    strPriceFile = "C:\Temp\File-2.xlsx"
    Set wbSrc = Workbooks.Open(strPriceFile)
    Set wsSrc = wbSrc.Worksheets("SOR2")

    LastRow = wsDst.Range("A" & wsDst.Rows.Count).End(xlUp).Row
    erow = LastRow + 1

    For i = 2 To LastRow
        If wsSrc.Cells(i, 1).Value = wsDst.Cells(i, 1).Value And _
           wsSrc.Cells(i, 2).Value = wsDst.Cells(i, 2).Value And _
           wsSrc.Cells(i, 3).Value = wsDst.Cells(i, 3).Value And _
           wsSrc.Cells(i, 4).Value = wsDst.Cells(i, 4).Value Then

            wsSrc.Cells(i, 12).Copy wsDst.Cells(erow, 12)
            erow = erow + 1  ' your current code would always copies to the same row,
                             ' but I **think** you probably want to copy to the
                             ' next row each time
        End If
    Next i

    wbSrc.Close
    If erow > LastRow + 1 Then
       wbDst.Save
    End If
    wbDst.Close
End Sub

该代码完全未经测试,但即使它不起作用,至少它应该让您了解应该如何处理多个工作簿和多个工作表。