VBA ElseIf有多个范围

时间:2015-03-11 16:45:43

标签: vba excel-vba excel

我有一个包含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

1 个答案:

答案 0 :(得分:1)

您可以使用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

...