Excel VBA查找列“C”包含已知值的最后一个行编号

时间:2015-01-25 02:02:52

标签: excel vba

在Excel VBA中寻找一个方法来查找列的最后一行编号" C"包含已知值。

2 个答案:

答案 0 :(得分:7)

这会在 C

列中找到最后出现的幸福
Sub SeekHappiness()
    Dim C As Range, where As Range, whatt As String
    whatt = "happiness"
    Set C = Range("C:C")
    Set where = C.Find(what:=whatt, after:=C(1), searchdirection:=xlPrevious)
    MsgBox where.Address(0, 0)
End Sub

要仅输出行号,请使用:

MsgBox Mid(where.Address(0, 0), 2)

要查找第一个事件:

Sub SeekHappiness()
    Dim C As Range, where As Range, whatt As String
    whatt = "happiness"
    Set C = Range("C:C")
    Set where = C.Find(what:=whatt, after:=C(1))
    MsgBox where.Address(0, 0)
End Sub

答案 1 :(得分:1)

您可以遍历该列以查找最后一次出现的值。

Sub findLastRow()
  Dim searchValue As String
  Dim endRow As Integer
  Dim lastRowSearchValue As Integer

  searchValue = "testValue"        ''enter your search value
  With Worksheets("sheet1")        ''enter the name of your worksheet
      endRow = .Cells(Rows.Count, 3).End(xlUp).Row   
      For i = 1 To endRow
          If .Cells(i, 3) = searchValue Then
              lastRowSearchValue = i
          End If
      Next i
  End With
End Sub

只需替换变量的值" searchValue"无论你正在寻找什么值(如果它不是一个字符串,可能会更改变量的类型),Sub会将searchValue出现的最后一行的索引存储在变量" lastRowSearchValue"供进一步使用。