VBA – 查找具有特定标题的列,并find该列中所有行的总和
我有一张大单。 我必须将该表中的多个filter设置为dynamic位置中的列标题。 一旦filter被设置,我必须find具有列标题“Nov”的工作表中的特定列,然后获得该列中的值的总和,并将该特定的总和值导入到不同的工作表中。 我已经写了代码,直到我可以将筛选器设置为多个列的部分,但是我发现很难find列标题并添加该列。 以下是我迄今为止编写的代码。
Sub Button2_Click() Dim colName As Long Dim colName1 As Long Dim colName2 As Long Dim r As Long SearchV = Range("A8:DD8").Find(What:="Nov", LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False).Column lastrow = Cells(Rows.Count, SearchV).End(xlUp).Row colName = Range("A8:DD8").Find(What:="Teams", LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False).Column colName1 = Range("A8:DD8").Find(What:="Items", LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False).Column colName2 = Range("A8:DD8").Find(What:="Domain", LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False).Column ActiveSheet.Range("$A$8:$DD$9999").AutoFilter Field:=colName, Criteria1:="ST Test", Operator:=xlOr, Criteria2:="" ActiveSheet.Range("$A$8:$DD$9999").AutoFilter Field:=colName1, Criteria1:="Variance", Operator:=xlOr, Criteria2:="(Blanks)" ActiveSheet.Range("$A$8:$DD$9999").AutoFilter Field:=colName2, Criteria1:="9S", Operator:=xlOr, Criteria2:="(Blanks)"
列标题始终从第8行开始。 一些无用的信息出现在上面的行中。 所以我想要的是,假设“Nov”这一列在H行。 总和应该从H9算到最后一行的末尾。 当列在“H”列时,我使用了这个公式。
Cells(lastrow + 1, colName3).Formula = "=SUBTOTAL(9,H9:H" & lastrow & ")"
但是'Nov'这个列不会总是出现在行'H'中,所以我无法弄清楚如何改变我的代码来dynamic地select列。
确保你完全限定你的对象,并且检查.Find
是否返回一些东西。 这是一个例子。
假设你的工作表看起来像这样
现在试试这个代码
Option Explicit Sub Sample() Dim ws As Worksheet Dim aCell As Range, Rng As Range Dim col As Long, lRow As Long Dim colName As String '~~> Change this to the relevant sheet Set ws = ThisWorkbook.Sheets("Sheet1") With ws Set aCell = .Range("A8:DD8").Find(What:="Nov", LookIn:=xlValues, LookAt:=xlWhole, _ MatchCase:=False, SearchFormat:=False) '~~> If Found If Not aCell Is Nothing Then col = aCell.Column colName = Split(.Cells(, col).Address, "$")(1) lRow = .Range(colName & .Rows.Count).End(xlUp).Row '~~> This is your range Set Rng = .Range(colName & "8:" & colName & lRow) Debug.Print Rng.Address '~~> If not found Else MsgBox "Nov Not Found" End If End With End Sub
产量