Excel VBA从一个工作表复制到给定多个条件的其他工作簿

时间:2017-11-02 19:08:24

标签: excel vba excel-vba

我知道这个问题与时间一样久,但我试图根据多个标准将excel文件中的数据复制到另一个文件。

目的地被称为" Test.xlsm"并且源被称为" Data.xlsx" 我们的想法是让代码识别在A列上有文本(1,3,D)的行,并将整行复制到目标Test.xlsm上的Sheet1

Test.xlsm上的第一行有一个标题,因此在将数据复制到该表时必须保留它。

这两个文件都在名为" Sheet1"的工作表上有目的地和来源信息。默认情况下。

我发现了这段代码,但是我无法使其适应源代码使用不同的工作表,尽管任何执行此目标的代码都可以。

Sub Copy()
Dim lr As Long, lr2 As Long, r As Long, ws1 As Worksheet, ws2 As Worksheet, n As Long
Application.ScreenUpdating = False
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
n = 1
lr = ws1.Cells(Rows.Count, "A").End(xlUp).Row
lr2 = ws2.Cells(Rows.Count, "A").End(xlUp).Row
    For r = 2 To lr
        If Range("A" & r).Value = "1" Or Range("A" & r).Value = "3" Or Range("A" & r).Value = "D" Then
            Rows(r).Copy Destination:=ws2.Range("A" & n + 1)
            n = ws2.Cells(Rows.Count, "A").End(xlUp).Row
        End If
    Next r
Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:0)

您也希望使用工作簿,因为您使用的是单独的工作簿,然后像您提供的示例一样设置工作表。

例如:

Dim wkbk1 as Workbook, wkbk2 as Workbook, ws1 as WorkSheet, ws2 as Worksheet
Set wkbk1 = Workbooks.open("C:\path\to\Data.xlsx")
Set wkbk2 = Workbooks.open("C:\path\to\Test.xlsm")

Set ws1 = wkbk1.Sheets("Sheet1")
Set ws2 = wkbk2.Sheets("Sheet1")

从那里你可以使用和修改你拥有的代码。

编辑:包含OP的工作簿和工作表名称。

答案 1 :(得分:0)

尝试此编辑或注释我根据评论中的要点进行了编辑 - 我认为这应该会很好!

Sub CopyThings()
Dim lr As Long, lr2 As Long, r As Long, ws1 As Worksheet, ws2 As Worksheet, n As Long
Application.ScreenUpdating = False
Set ws1 = Application.Workbooks("Data").Worksheets("Sheet1")
Set ws2 = Application.Workbooks("Test").WorkSheets("Sheet1")
n = 1
lr = ws1.Cells(Rows.Count, "A").End(xlUp).Row
lr2 = ws2.Cells(Rows.Count, "A").End(xlUp).Row
    For r = 2 To lr
        If ws1.Range("A" & r).Value = "1" Or ws1.Range("A" & r).Value = "3" Or ws1.Range("A" & r).Value = "D" Then
            ws1.Rows(r).Copy Destination:=ws2.Range("A" & n + 1)
            n = ws2.Cells(Rows.Count, "A").End(xlUp).Row
        End If
    Next r
Application.ScreenUpdating = True
End Sub