2013-12-12 37 views
2

我有這個子作用於列A,A1到最後一行數據和改變這些細胞爲「文本」的值:使用列號代替範圍內的A1?

Sub Sample() 
    Dim lastRow As Long 
    lastRow = Range("A" & Rows.Count).End(xlUp).Row 
    Range("A1:A" & lastRow).Value = "text" 
End Sub 

是否有使用R1C1表示法的範圍中的方法而不是A1標記來定義列?

我希望最終使用一個變量作爲列號,並逐步執行重複操作,然後在具有數據的最後一列停止。

相反,是否最好保留A1表示法,因爲您可以指示我使用A1表示法來遍歷列的方法嗎?

我很抱歉,如果這是一個頭腦問題,我已經搜索了幾天發佈。對初學者感到可惜。 :) 謝謝, Chuck

@Siddarth,非常感謝,你的代碼讓我朝着正確的方向前進。使用你的第二個Sub我發現它將所有單元格的值更改爲「文本」。我有興趣一次操縱一列,並修改代碼以僅更改列A,您是否看到任何語法問題?

Sub Sample2() 
    Dim ws As Worksheet 
    Dim rng As Range 
    Dim LastCol As Long, LastRow As Long 

    Set ws = ThisWorkbook.Sheets("Results") 

    With ws 
     LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 
     LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 

     Set rng = .Range(.Cells(1), .Cells(LastRow, 1)) 

     Debug.Print rng.Address 

     rng.Value = "text" 
    End With 
End Sub 

隨後我命名一個變量,我希望步驟和小組仍然有效:

Sub Sample2A() 
    Dim ws As Worksheet 
    Dim rng As Range 
    Dim LastCol As Long, LastRow As Long 
    Dim StarttCol As Integer 

    StarttCol = 1 

    Set ws = ThisWorkbook.Sheets("Results") 

    With ws 
     LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 
     LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 

     Set rng = .Range(.Cells(StarttCol), .Cells(LastRow, StarttCol)) 

     Debug.Print rng.Address 

     rng.Value = "text" 
    End With 
End Sub 
+1

要小心詢問什麼是首選,因爲它會使您的問題面臨主要基於意見而被關閉的風險。 – 2013-12-12 15:10:23

回答

2

您可以使用列名稱/號碼,而不必使用RC符號。例如

Sub Sample() 
    Dim ws As Worksheet 
    Dim rng As Range 
    Dim LastCol As Long, LastRow As Long 
    Dim LastColumn As String 

    Set ws = ThisWorkbook.Sheets("Results") 

    With ws 
     LastRow = .Range("A" & .Rows.Count).End(xlUp).Row 
     LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 

     '~~> Return column name from number 
     LastColumn = Split(.Cells(, LastCol).Address, "$")(1) 

     Set rng = .Range("A1:" & LastColumn & LastRow) 

     Debug.Print rng.Address 

     rng.Value = "text" 
    End With 
End Sub 

相同的代碼也可被寫爲

Sub Sample() 
    Dim ws As Worksheet 
    Dim rng As Range 
    Dim LastCol As Long, LastRow As Long 

    Set ws = ThisWorkbook.Sheets("Results") 

    With ws 
     LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 
     LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 

     Set rng = .Range(.Cells(1, 1), .Cells(LastRow, LastCol)) 

     Debug.Print rng.Address 

     rng.Value = "text" 
    End With 
End Sub 
+0

+1非常不錯的用法與變量。 – 2013-12-12 15:09:39

+0

@Siddarth,非常感謝,你的代碼讓我朝着正確的方向前進。使用你的第二個Sub我發現它將所有單元格的值更改爲「文本」。我有興趣一次操作一列,並將代碼修改爲僅更改列A. – user3095743

+0

那麼,您的查詢是否已解決,或者您仍有問題? –

0

只需使用細胞指定的範圍內。例如:範圍(A1)==範圍(將細胞(1,1))

喜歡的東西範圍(A1:A10)。將範圍(細胞(1,1),將細胞(1,10))

相關問題