2013-03-12 54 views
0

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

+1

你有什么试过的?也许记录一个宏,然后尝试编辑它,然后问你一个问题,而不是要求代码 – scott 2013-03-12 15:50:33

回答

1

对于你来说是否有点棘手,因为你没有尝试,或者因为你尝试过并且无法弄清楚它?如果你首先提供你的代码,那么总是很好,这样我们就可以看到你在做什么以及我们如何才能使它工作。

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

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

+0

你好山姆。在我发布任何关于Stackoverflow的问题之前,我总是试着自己解决这个问题。不是每次我能够做到这一点,那么我来到这里。我的大部分问题都是我现在的代码。但是,我对VBA的知识有限,所以在这种特殊情况下,我无法修改我在互联网上发现的代码,甚至接近我希望达到的状态。无论如何,你的代码在F2中提供了结果,但这并不是我所要求的,因为我有这种类型的代码。我唯一需要的是在测试列中选择最后一个值。 – mgunia 2013-03-12 17:16:16

+0

通常是一个好主意,然后张贴你试过的东西,这样我们就可以看到它,并在需要的地方引导你朝着正确的方向前进。让代码将最后一个值输出到“F2”中是为了向您展示它的工作原理。如果您只需要选择最后一个单元格,那么您可以使用'Cells(lastRowInSearchColumn,searchColumn).Select'来代替'Range(“F2).Value = ...' – Sam 2013-03-12 18:05:05

+0

它工作的非常好!我明白一个没有代码的帖子就显得有些尴尬,但正如前面提到的那样,我不能拿出任何有价值的东西。谢谢萨姆帮助我,即使我提出了这么几个细节,我很感激 – mgunia 2013-03-13 08:47:56

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 
+0

同意,做一件事的方法很多,+1选择更短,更简单的路线;) – Sam 2013-03-12 18:11:03

相关问题