2013-11-21 97 views
5

我有一個大表。我必須將該表中的多個過濾器設置爲動態位置中的列標題。一旦設置了過濾器,我必須在具有列標題「Nov」的工作表中找到特定的列,然後獲取該列中的值的總和,並將該特定的總和值導入到不同的工作表中。 我已經寫了代碼,直到我可以將篩選器設置爲多個列的部分,但我發現很難找到列標題並添加該列。以下是我迄今爲止編寫的代碼。VBA - 查找具有特定標題的列並找到該列中所有行的總和

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 & ")" 

但列「月」不會永遠存在於行「H」,所以我無法弄清楚如何改變我的代碼來接動態列。

回答

7

確保您完全符合您的對象,並且還要檢查.Find是否返回某些內容。這是一個例子。

比方說,您的工作表看起來像這樣

enter image description here

現在試試這個代碼

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 

輸出

enter image description here

+0

非常感謝您的幫助Siddh ARTH。我設法完成了我的大部分工作。但實際的問題是管理添加行的總和。我現在正在使用此代碼。 'SumV = SV& 「9:」' 'SumW = SV&lRow' '細胞(lRow + 1,SV).Formula = 「= SUBTOTAL(9,SumV:SumW)」' 但是,這是Excel中返回以下值「= SUBTOTAL(9,SumV:SumW)」 而我越來越#NAME?錯誤。 –

+0

嗯,什麼是'SV'? –

+0

對不起,我不清楚。不管你在代碼中提到了colName,我將它重命名爲SV,因爲我已經在其他地方使用了colName變量。所以基本上,我試圖做的是連接列和行以獲得一定的值(例如W9)。 所以我得到SumW的W9和SumW的W2128的值。但是,當我使用小計功能時,同樣插入,而不是實際值。我也嘗試過使用它們。 '= SUBTOTAL(9,「&SumV&」:「&SumW&」)'。但即使這是拋出一個例外。 –

相關問題