根据行和列字符串动态抓取单元格

时间:2017-07-27 19:29:39

标签: arrays excel vba excel-vba variables

我有一个跨列的月份表。这几个月总是在变化,所以我试图调整我的代码来适应这个。如果列保持静态,它的效果很好,我只需要弄清楚如何动态地找到哪一列是总列。

这是我到目前为止所拥有的:

Sub CalculateTotalGP()

For RowToTest = Cells(Rows.count, 27).End(xlUp).Row To 2 Step -1
        With Cells(RowToTest, 27)
            If .Value = "GP%" Then
            Range("AL" & RowToTest & ":AL" & RowToTest).Formula = "=SUMIFS(AL:AL,AA:AA,""GrossProfit Total"")/SUMIFS(AL:AL,AA:AA,""Income Total"")"
        End If
            End If
        End With
Next RowToTest

End Sub

为了用变量替换“AL”,我需要抓住什么:

InStr(1, Cells(6, i), "Total")

基本上无论总列在指定范围内的哪个位置,都输入该公式。唯一保持静态的是我的列范围,从AD8到AS9999(或N)的16列和我从AA列开始的标准。

你能帮我搞清楚吗?

谢谢

1 个答案:

答案 0 :(得分:1)

要获取标题“Total”的列号,请使用GetHeaderCol()函数(而不是Match)

Option Explicit

Public Sub TestHeader()
    Dim tHeader As Long

    tHeader = GetHeaderCol(Sheet1, "Total", 6)  'If "Total" in row 6 & col H, result -> 8

    If tHeader > 0 Then Debug.Print "Total column: " & tHeader
End Sub
Public Function GetHeaderCol(ByRef ws As Worksheet, ByVal hdr As String, _
                             Optional ByVal hdrRow As Long = 1) As Long

    Dim hdrs As Variant, c As Variant

    If ws Is Nothing Then Set ws = ActiveSheet
    hdrRow = IIf(hdrRow = 0, 1, Abs(hdrRow))
    hdrs = ws.Range(ws.Cells(hdrRow, 1), ws.Cells(hdrRow, Columns.Count).End(xlToLeft))

    If Not IsEmpty(hdrs) Then
        For c = 1 To UBound(hdrs, 2)
            If InStr(1, hdrs(1, c), hdr, vbTextCompare) > 0 Then
                GetHeaderCol = c
                Exit Function
            End If
        Next
    End If
    GetHeaderCol = 0
End Function