根据列标题在最后一个单元格中查找值

时间:2015-08-19 01:57:59

标签: excel vba excel-vba

我正在尝试构建一个宏,它可以根据列标题(“TOTAL”)(工作表名称:FIL)查找并复制最后一个单元格,并将其复制到另一个工作表中的特定单元格(B2)(表格名称:MACRO TEMPLATE)。我找到了它的代码,但它没有复制另一张表中的值。我尝试调整它以使其工作但没有运气(代码在同一工作表(FIL)上的命令按钮工作,但如果放在另一个工作表(MACRO模板),代码不起作用。)。

我还有另一个关于代码的问题。标题所在的单元格被合并(第9行和第10行)。是否可以按列搜索而不是查找标题行,以便合并的单元格不受影响?任何帮助将不胜感激。

以下是代码:

Dim headerRow As Integer
Dim totalColumnsInHeaderRow As Integer
Dim searchColumn As Integer
Dim lastRowInSearchColumn As Integer
Dim columnSearchString As String
With Sheets("FIL")
headerRow = 9   
totalColumnsInHeaderRow = Sheets("FIL").Cells(headerRow, Columns.Count).End(xlToLeft).Column
columnSearchString = "TOTAL" 
searchColumn = 0


Dim currentColumn As Integer
For currentColumn = 1 To totalColumnsInHeaderRow

    If StrComp(Sheets("FIL").Cells(headerRow, currentColumn).value, columnSearchString, vbTextCompare) = 0 Then

        searchColumn = currentColumn
        Exit For
    End If
Next


If searchColumn > 0 Then
    'Set F2 equal to the last value in that column
    lastRowInSearchColumn = Sheets("FIL").Cells(Rows.Count, searchColumn).End(xlUp).Row
    Sheets("MACRO TEMPLATE").Range("B2").value = Cells(lastRowInSearchColumn, searchColumn).value
End If

End With

1 个答案:

答案 0 :(得分:0)

关闭End IfEnd With之前的最后一行包含Cells(lastRowInSearchColumn, searchColumn).Value。如果这应该来自 FIL 工作表?

您使用的是With ... End With statement,但没有利用它提供的父工作表参考机会。

Dim headerRow As Long
Dim totalColumnsInHeaderRow As Long
Dim searchColumn As Long
Dim lastRowInSearchColumn As Long
Dim currentColumn As Long
Dim columnSearchString As String

With Sheets("FIL")
    headerRow = 9
    totalColumnsInHeaderRow = .Cells(headerRow, Columns.Count).End(xlToLeft).Column
    columnSearchString = "TOTAL"

    searchColumn = 0
    For currentColumn = 1 To totalColumnsInHeaderRow
        If StrComp(.Cells(headerRow, currentColumn).Value, columnSearchString, vbTextCompare) = 0 Then
            searchColumn = currentColumn
            Exit For
        End If
    Next currentColumn

    If searchColumn > 0 Then
        'Set F2 equal to the last value in that column
        lastRowInSearchColumn = .Cells(Rows.Count, searchColumn).End(xlUp).Row
        Sheets("MACRO TEMPLATE").Range("B2") = _
            .Cells(lastRowInSearchColumn, searchColumn).Value
    End If
End With

请注意,任何Range.Cells property只需要一段时间(也就是句号或.),以便工作表为With ... End With语句指定其父工作表。这并不能阻止您在特殊情况下指定另一个工作表,如上一个值传输目标