2017-06-22 123 views
0

我想使用創建的命名範圍確定範圍內最後一次使用的行。Excel VBA:使用命名範圍確定上次使用的行

這是我如何做到這一點。

With ActiveSheet 
    Dim textboxValue As String, lastUsedRow As Long 
    textboxValue = UserForm.TextBox1 
    lastUsedRow = .Range(textboxValue).Rows.Count 
    Cells(lastUsedRow).Select 
End With 

enter image description here 這是什麼在工作表,以便最後使用的行應該是一個字「不」。

enter image description here 但是,選定的最後一次使用的行是一個沒有任何內容的單元格。

+0

[Excel VBA中的查找範圍內最後一行(的可能的複製https://stackoverflow.com/questions/40650508/excel-vba-find-last -row-in-range) – danieltakeshi

+0

'Cells(lastUsedRow)' - 你沒有提供一行和一列 –

+0

如果我放一列,它仍然是錯誤的單元格。不同的細胞,但仍然是錯誤的。 –

回答

0

一種可能的方式是這樣的......

Dim rng As Range 
Dim textboxValue As String, lastUsedRow As Long, i As Long 
With ActiveSheet 
    textboxValue = UserForm.TextBox1 
    Set rng = .Range("textboxValue") 
    For i = rng.Cells(1).Offset(rng.Cells.Count - 1).Row To rng.Cells(1).Row Step -1 
     If .Cells(i, rng.Columns(1).Column) <> "" Then 
      lastUsedRow = .Cells(i, rng.Columns(1).Column).Row 
      MsgBox lastUsedRow 
      .Cells(i, rng.Columns(1).Column).Select 
      Exit Sub 
     End If 
    Next i 
    If lastUsedRow = 0 Then 
     MsgBox "textboxValue range is completely empty.", vbExclamation 
    End If 
End With