0

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

4

2 回答 2

1

对你来说很棘手是因为你没有尝试,还是因为你尝试了但无法弄清楚?如果您先提供您的代码总是很好的,这样我们就可以看到您到底在做什么以及我们如何帮助它工作。

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

代码

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

在此处输入图像描述

在此处输入图像描述

于 2013-03-12T15:50:50.227 回答
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
于 2013-03-12T16:13:09.503 回答