2015-04-06 147 views
0

我想選擇最後一個單元格(最後一行,最後一列)。範圍內的變量

Range(ColumnName & Rows.Count).End(xlUp).Select 

ColumnName是按字母順序排列的最後一列(例如:D)。

這不起作用。但是,這是:

Range("D" & Rows.Count).End(xlUp).Select 

編輯:

'colNum as integer (e.g: 4) 
'this code transform number to alphabetical 

Public Function ColumnName(colNum As Integer) As String 
Dim d As Integer 
Dim m As Integer 
Dim name As String 
d = colNum 
name = "" 
Do While (d > 0) 
    m = (d - 1) Mod 26 
    name = Chr(65 + m) + name 
    d = Int((d - m)/26) 
Loop 
ColumnName = name 
'If i do  "MsgBox ColumnName", and "MsgBox CStr(Len(ColumnName))" I obtain D, and 1. 
End Function 
+0

哪裏是你的一個字符串的聲明 – 2015-04-06 11:36:31

+0

我的猜測是,你正在使用,以找到最後一列返回數值R1C1風格,通過一系列功能解析您收到錯誤時,爲什麼結果的公式。我的解決方案可以解決您的問題。 – izzymo 2015-04-06 11:57:59

+0

而不是'Range(ColumnName&Rows.Count).End(xlUp).Select'你應該嘗試'Cells(Rows.Count,ColumnName).end(xlUp).select'替代解決方案。僅供參考,您甚至不需要將列號轉換爲列名並保存多行代碼 – izzymo 2015-04-06 12:40:09

回答

0

您將不得不聲明ColumnName作爲變量。

Sub Button1_Click() 
    Dim ColumnName As String 
    ColumnName = "D" 
    Range(ColumnName & Rows.Count).End(xlUp).Select 
End Sub 

這是一個更流行的方式來做到這一點。

Sub SelectLastCellInColumnOption() 
    Dim Rws As Long 
    Rws = Cells(Rows.Count, "D").End(xlUp).Row 
    Cells(Rws, "D").Select 
End Sub 
+0

我編輯帖子以獲取更多信息。我試過你的代碼,但我不知道爲什麼不行 – user4563174 2015-04-06 12:15:32

0

應該有沒有"D"與價值"D"一個字符串變量之間的差異,因此,我建議,也許你的論點,即ColumnName"D"可能不正確。請徹底檢查一下。

你可以像這樣做:

MsgBox ColumnName 
MsgBox CStr(Len(ColumnName)) 

,並確保你得到D1作爲結果。

+0

我使用更多信息編輯帖子 – user4563174 2015-04-06 12:05:21

0

要找到最後一個單元,你可以試試這個。這不完全是你的代碼的修正,但下面的結果將幫助你選擇當前表中的最後一個單元格,如果我從第一句正確理解是你的問題。

Dim LCol As Long 
LCol = Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column 
Cells(Rows.Count, LCol).End(xlUp).Select