简体   繁体   English

如何从VBA中的多个列复制和粘贴

[英]how to copy and paste from multiple columns in vba

I'm trying to copy data from columns C,D,J,P when the value in column I is "O" 我正在尝试从列C,D,J,P中复制数据,而列I中的值为“ O”

I'm very new at VBA and the best approach I could think of what to use an IF statement, but I haven't been able to paste more than two consecutive columns. 我是VBA的新手,是我可以想到的使用IF语句的最佳方法,但是我无法粘贴超过两个连续的列。

sub firsttry
Dim bodata As Worksheet
Dim bopresentation As Worksheet

Set bodata = Worksheets("BO Data")
Set bopresentation = Worksheets("BO presentation")

bodata.Activate

Dim i As Integer
i = 1

For i = 1 To 20
If bodata.Cells(i, 9).Value = "O" Then
bodata.Range(Cells(i, 3), Cells(i, 4)).Copy

bopresentation.Range("b20").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteAll)

Else
End if
Next

end sub

Range doesn't work like that: try this: Range不能那样工作:尝试以下方法:

For i = 1 To 20

    If bodata.Cells(i, 9).Value = "O" Then

        Application.Union(bodata.Cells(i, 3), bodata.Cells(i, 4), _
                          bodata.Cells(i, 10), bodata.Cells(i, 16)).Copy

        bopresentation.Range("b20").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteAll)


    End if

Next

Your approach itself is exactly right. 您的方法本身就是正确的。 Looping over a range of cells is usually the most efficient way of handling data. 在单元格范围内循环通常是处理数据的最有效方法。 In your current code you'd simply need to repeat the copy for the cells missing inside the loop. 在当前代码中,您只需要为循环中缺少的单元格重复复制。

In VBA, however, "pasting" in a seperate line of code if rarely necessary. 但是,在VBA中,如果极少需要,可以在单独的代码行中“粘贴”。 It is also good coding practise to define all your variables at the top of your code. 在代码顶部定义所有变量也是一种良好的编码习惯。

Here is different approach using the For each -loop and summing up the wanted range with the Union method: 这是使用For each Each循环并使用Union方法将所需范围求和的不同方法:

Dim rCell as Range
Dim rSource as Range


'Define the source range as the entire column C
With ThisWorkbook.Worksheets("BO Data")
    Set rSource = .Range("C1", .Cells(Rows.Count, 3).End(xlUp))
End with

'Loop over each cell in the source range and check for its value
For each rCell in rSource
    If rCell.Value = "0" Then
        'If requirement met copy defined cells to target location
        With ThisWorkbook.Worksheets("BO Data")
            Application.Union(.Cells(rCell.Row, 3), _
                              .Cells(rCell.Row, 4), _
                              .Cells(rCell.Row, 10), _
                              .Cells(rCell.Row, 16) _
            ).Copy Destination = ThisWorkbook.Worksheets("BO Presentation").Range("B2")
        End With
Next rCell

This, of course, loops over all cells in Column C. If you want to limit the range, you can simply adjust rSource to your needs. 当然,这会循环遍历C列中的所有单元。如果要限制范围,可以简单地将rSource调整为需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM