2011-07-20 60 views
0

我有一個Excel宏如下:Excel宏 - 忽略列標題?

Private Sub CommandButton1_Click() 
Application.ScreenUpdating = False 
Dim i&, j&, k&, LR_A&, LR_B&, LR_C&, count& 

LR_A = Range("A" & Rows.count).End(xlUp).Row 
LR_B = Range("B" & Rows.count).End(xlUp).Row 
LR_C = Range("C" & Rows.count).End(xlUp).Row 
count = 1 

For i = 1 To LR_A 
    For j = 1 To LR_B 
    For k = 1 To LR_C 
     Range("D" & count).Value = Range("A" & i).Value 
     Range("E" & count).Value = Range("B" & j).Value 
     Range("F" & count).Value = Range("C" & k).Value 
     count = count + 1 
    Next k 
    Next j 
Next i 
Application.ScreenUpdating = True 
End Sub 

正如你所看到的,它是在列A,B和C的數據訴諸到d,E和F

做些什麼碼我需要添加它才能忽略A,B和C中的列標題?我已經四處搜尋,但一直未能找到答案。

此外,我將如何改變它,使它不是將數據轉化爲D,E和F,而是將它轉化爲另一個工作表上的A,B和C?

這是我的第一個宏,所以它們是非常基本的問題。

在此先感謝

回答

0

回答你的問題

爲了避免複製標題,你應該在指數2開始你的循環。
要將值複製到另一個Worksheet,您需要在您的Range中調用它。

For i = 2 To LR_A 
    For j = 2 To LR_B 
    For k = 2 To LR_C 
     Sheets("My other ws").Range("D" & count).Value = Range("A" & i).Value 
     Sheets("My other ws").Range("E" & count).Value = Range("B" & j).Value 
     Sheets("My other ws").Range("F" & count).Value = Range("C" & k).Value 
     count = count + 1 
    Next k 
    Next j 
Next i 

也許有更好的方式來處理這種情況

使用指數可能會很慢循環執行範圍。
我建議你看看這個鏈接:http://www.ozgrid.com/VBA/VBALoops.htm作者解釋了更快的方法來循環範圍。

一些技巧

看一看的Excel SpecialCells描述here
例如,對於您的情況,您可以嘗試使用而不是查找上次使用的行。

+0

我會研究其他方法,但您對宏的建議根本無法使用。當我將工作表內容放入範圍時,Excel突然給我提供錯誤「編譯錯誤:函數或子未定義」。即使我把它拿出來,只讓i,j和k設置爲2,宏也不會再運行了。 – Billy

+0

@比利:對不起,我編輯了我的代碼。我在'Sheets'語法上犯了一個錯誤 – JMax

+0

啊,我明白了。非常感謝!另外,感謝其他內容的鏈接,我也會使用它。 – Billy