2017-06-04 27 views
1

喜歡使用Cells(1, 1),而不是Range("A1"),有什麼用/列索引範圍在VBA的最佳方式?如何使用列/行索引範圍在VBA

我想出了兩個解決方法來表示範圍( 「A:A」):

  • Range(Cells(1, 1), Cells(Columns(1).Rows.count, 1))
  • Union(Columns(1), Columns(1))

有沒有更好更簡潔的解決方案?

編輯:注意到Tehscript的迴應,並感謝相同。我已經嘗試過,但它給下面的錯誤:

Run-time error '13': Type mismatch.

下面的代碼:

Sub tfind() 
    Dim r1 As Range 
    Set r1 = Columns(1) 
    MsgBox mCount("Test:", r1) 
End Sub 
Function mCount(find As String, lookin As Range) As Long 
    Dim cell As Range 
    For Each cell In lookin 
     If (Left(cell.Value, Len(find)) = find) Then mCount = mCount + 1 
    Next 
End Function 

雖然它工作正常,如果3號線:

Set r1 = Columns(1) 

改爲:

Set r1 = Union(Columns(1), Columns(1)) 
+0

如果你已經張貼你的代碼前面,它會更容易得到正確的答案。你所尋找的是'.Cells' – Tehscript

+0

完美! thanx再次 – curious

回答

3

有做T沒有最好的方法他的,但有些方法可以根據你的需要使用。例如,如果你想通過行和列循環,你應該更好地利用Cells()

Sub RowTimesColumn() 
Dim i As Long, j As Long 
For i = 1 To 10 
    For j = 1 To 5 
     Cells(i, j) = i * j 
    Next j 
Next i 
End Sub 

在另一方面,你可以在任一方式引用了一系列像Range("A1:B3")根據您的需要。如果您只需要參考,則應使用Range("A1:B3")。如果您需要的行和列玩,你應該更好地使用Range(Cells(1, 1), Cells(3, 2))

這是所有關於可讀性和功能。

對於你的問題,你可能想使用以下命令:

  • Range("A:A") - >Columns(1)

  • Range("A:C") - >Range(Columns(1), Columns(3))

編輯:你循環遍歷列A中的單元格,在這種情況下,您需要使用方法:

  • Columns("A").CellsColumns(1).Cells