根据行和列stringdynamic抓取单元格
我有一张桌子上有几个月的表。 月份总是在转移,所以我正在尝试调整我的代码以适应这一点。 如果列保持静态的话,它的工作效果很好,我只需要弄清楚如何dynamic地find哪一列是总列。
以下是我到目前为止:
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
我需要抓住一个variables来代替“AL” :
InStr(1, Cells(6, i), "Total")
基本上无论列的总数在哪个范围内,都要input该公式。 唯一保持不变的是我的列范围,从AD8到AS9999(或N)的16列和从列AA的标准。
你能帮我弄清楚吗?
谢谢
要获得头“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