在指定列的最后一个单元格中查找值(根据其标题)

时间:2013-03-12 15:32:21

标签: excel vba

我有点棘手(对我而言)要完成的任务。我想创建一个宏,它将在指定列的最后一个单元格中找到一个值(根据其标题)。例如,它将在名为“test”的列中找到最后一个值。

2 个答案:

答案 0 :(得分:1)

对你来说是不是很棘手,因为你没有尝试过,或者是因为你试过并且无法解决这个问题?如果您首先提供代码,这总是很好,这样我们就能看到您正在做什么以及我们如何帮助它发挥作用。

无论如何,这是我放在一起做你要求的东西。它假设我们将在Sheet 1中进行搜索。在Visual Basic Editor (VBE)中,打开Sheet1并粘贴此代码。然后,您可以像常规宏一样使用它(请务必更改标题值和搜索字符串以满足您的需求)。

<强> CODE

Public Sub FindValueInColumn()

    Dim headerRow As Integer
    Dim totalColumnsInHeaderRow As Integer
    Dim searchColumn As Integer
    Dim lastRowInSearchColumn As Integer
    Dim columnSearchString As String

    headerRow = 1   'change this to correct header row
    totalColumnsInHeaderRow = Cells(headerRow, Columns.Count).End(xlToLeft).Column
    columnSearchString = "Test" 'change to the text to search
    searchColumn = 0

    'for every column that has a value in it in the header row
    Dim currentColumn As Integer
    For currentColumn = 1 To totalColumnsInHeaderRow
        'if that value equals what we're looking for (in this case, "Test")
        If StrComp(Cells(headerRow, currentColumn).Value, columnSearchString, vbTextCompare) = 0 Then
            'save the column that contains the value, then exit the loop
            searchColumn = currentColumn
            Exit For
        End If
    Next

    'if the column of interest exists in the header row
    If searchColumn > 0 Then
        'Set F2 equal to the last value in that column
        lastRowInSearchColumn = Cells(Rows.Count, searchColumn).End(xlUp).Row
        Range("F2").Value = Cells(lastRowInSearchColumn, searchColumn).Value
    End If

End Sub

<强> BEFORE

enter image description here

<强> AFTER

enter image description here

答案 1 :(得分:1)

我真的很喜欢看到不同的编码风格。显然,有很多方法可以给这只猫皮肤。

Sub Last_Cell_In_Column()
   Dim sh As Worksheet
   Dim col As Long

   Set sh = ThisWorkbook.ActiveSheet
   col = 0
   col = sh.Rows(1).Find("test").Column
   If col > 0 Then
      MsgBox (sh.Cells(sh.Rows.Count, col).End(xlUp).Value)
   End If
End Sub