[英]VBA ElseIf with multiple ranges
我有一个文件,数据在A-U和W-AA中。 我正在尝试编写将复制第一个范围A-U中的单元格的代码,一旦遇到A中的空白单元格,它将查找第二个范围W-AA。 代码的第一部分正在工作,但是我似乎无法弄清楚如何调用第二个范围。
Sub Test()
Dim rowCount2 As Long, shtSrc As Worksheet
Dim shtDest As Worksheet
Dim rng2 As Range
Dim rng3 As Range
Dim currentRow As Long
Set shtSrc = Sheets("Data")
Set shtDest = Sheets("Audit")
rowCount2 = shtSrc.Cells(Rows.Count, "A").End(xlUp).Row
Set rng2 = shtSrc.Range("A1:A" & rowCount2)
Set rng3 = shtSrc.Range("W1:W" & rowCount2)
currentRow = 2
For Each cell2 In rng2.Cells
If cell2.Value <> "" Then
shtDest.Range("B" & currentRow).Value2 = cell2.Value2
shtDest.Range("C" & currentRow).Value2 = cell2.Offset(0, 1).Value2
shtDest.Range("G" & currentRow).Value2 = cell2.Offset(0, 2).Value2
currentRow = currentRow + 1
ElseIf cell2.Value = "" Then
shtDest.Range("B" & currentRow).Value2 = cell2.Value2
shtDest.Range("C" & currentRow).Value2 = cell2.Offset(0, 1)
currentRow = currentRow + 1
End If
Next cell2
End Sub
您可以只使用offset函数到达相应的列:
Dim RangeDiff As Integer
...
Set rng2 = ...
Set rng3 = ...
RangeDiff = Rng3.Column - rng2.column
...
ElseIf cell2.Value = "" Then
shtDest.Range("B" & currentRow).Value2 = cell2.Offset(0, RangeDiff).Value2
shtDest.Range("C" & currentRow).Value2 = cell2.Offset(0, RangeDiff + 1)
...
根据对需求的新理解进行编辑:
...
For Each cell2 In rng2.Cells
If cell2.Value <> "" Then
shtDest.Range("B" & currentRow).Value2 = cell2.Value2
shtDest.Range("C" & currentRow).Value2 = cell2.Offset(0, 1).Value2
shtDest.Range("G" & currentRow).Value2 = cell2.Offset(0, 2).Value2
currentRow = currentRow + 1
ElseIf cell2.Value = "" Then
Exit For
End If
Next cell2
For Each cell3 In rng3.Cells
If cell3.Value <> "" Then
shtDest.Range("B" & currentRow).Value2 = cell3.Value2
shtDest.Range("C" & currentRow).Value2 = cell3.Offset(0, 1).Value2
shtDest.Range("G" & currentRow).Value2 = cell3.Offset(0, 2).Value2
currentRow = currentRow + 1
ElseIf cell3.Value = "" Then
Exit For
End If
Next cell3
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.