我创建了以下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
不起作用。
下面是一些截图,作为解释:
答案 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