VBA Do Loop不起作用

时间:2017-06-20 21:15:03

标签: excel-vba loops vba excel

我创建了以下Do循环:

    Sub Test2()
Set sht = Worksheets("Calculations")
LastRow = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row + 1
LastCol = (LastRow - 2) * 3
i = 1
r = 3
c = 5

Do Until r > LastRow
    sht.Cells(r, c).Select
    RangeName = "Airline_" & i
    Set Cell = sht.Cells(r, 5)
    sht.Names.Add Name:=RangeName, RefersTo:=Cell
        Do Until c > LastCol
            RangeName = "Airline_" & i
            Set Cell = Application.Union(Range("Airline_" & i), sht.Cells(r, c))
            sht.Names.Add Name:=RangeName, RefersTo:=Cell
        c = c + 3
        Loop
    i = i + 1
    r = r + 1
Loop

End Sub
乍一看,一切似乎都没问题。但是当r变为4时,看起来Do until c > LastCol不起作用。

下面是一些截图,作为解释:

第一行,有效: Screenshot 1 (working row)

第二行,不起作用: Screenshot 2 (not working)

1 个答案:

答案 0 :(得分:2)

我更喜欢FOR循环。

还有很多冗余。

Sub Test2()
Dim sht As Worksheet
Dim Lastrow&, LastCol&
Dim r&, c&
Dim RangeName as String

Set sht = Worksheets("Calculations")
Lastrow = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row + 1
LastCol = (Lastrow - 2) * 3 'need to be careful with this, too many rows will go off the page in columns.


For r = 3 To Lastrow
    RangeName = "Airline_" & r - 2
    Set cell = sht.Cells(r, 5)
    For c = 8 To LastCol Step 3
        Set cell = Union(cell, sht.Cells(r, c))
    Next c
    sht.Names.Add Name:=RangeName, RefersTo:=cell
Next r

End Sub