2017-06-20 83 views
0

我創建了以下Do循環:VBA 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

你可能需要開始前設置爲'c = 5'你'做,直到C> LastCol'循環,否則'C'仍然有它曾在以前的循環結束的值。 (我不確定你的'sht.Cells(r,c).Select'的目的是什麼 - 你可能實際上需要在該行之前設置'c = 5',但是移動它可能會更好)。 – YowE3K

回答

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 
+0

繼續前進 - 擺脫'RangeName'並將其設置在'Name:='(或至少聲明它!) – YowE3K

+0

知道我已經錯過了一。我更喜歡使用變量,因爲它有助於調試。 @ YowE3K –

+0

公平 - 我還擔心'拉斯特羅= ... + 1' - 這看起來像一個巧克力,以至於'LastCol'計算正確 – YowE3K