[英]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.