当第I列中的值为" O"
时,我试图从列C,D,J,P复制数据我是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
答案 0 :(得分:0)
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
答案 1 :(得分:0)
你的方法本身是完全正确的。循环一系列单元通常是处理数据的最有效方式。在您当前的代码中,您只需要重复循环中缺失的单元格的副本。
然而,在VBA中,"粘贴"如果很少需要,在一个单独的代码行中。在代码顶部定义所有变量也是一种很好的编码实践。
以下是使用For 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
当然,这会循环到C列中的所有单元格。如果要限制范围,可以根据需要调整rSource。