2014-10-02 128 views
0

我想在VBA中使用Sumif函數,但是,我得到一個運行時錯誤。當我嘗試將變量CritLastCol添加到公式中時,錯誤就開始了。如果我用實際的單元格引用替換它,它就可以工作。我希望能夠自動填充下面的行,並且我的標準將根據行進行更改。換句話說,我的總和範圍和標準範圍是固定的,我的標準是活動單元左側的單元格(但沒有一個結束,它可能是20,30列)。運行時錯誤1004 SumIf函數

Sub SumBydimcode() 
Dim lastCol As Integer 
Dim CritLastCol As String 
lastCol = Cells(3 & Columns.Count).End(xlToLeft).Column 
lastRow = Range("A" & Rows.Count).End(xlUp).Row 
NewLastRow = Range("I" & Rows.Count).End(xlUp).Row 
CritLastCol = ActiveCell.End(xlToLeft).Value 

    ActiveCell.FormulaR1C1 = "=SUMIF(R3C8:R" & lastRow & "C8," & CritLastCol & ",R3C10:R" & lastRow & "C" & lastCol & ")" 

    ActiveCell.AutoFill Destination:=Range(ActiveCell.Address & ":J" & NewLastRow) 

End Sub 
+0

你可以將一個值放入CritLastCol工作嗎?使用CritLastCol =「WhatYouWant」進行測試# – Smandoli 2014-10-02 21:34:21

回答

0

您需要將引號中的CritLastCol變量包圍起來。要在VBA中這樣做,請使用兩次雙引號""。其結果是,你的代碼應該是這樣的:

ActiveCell.FormulaR1C1 = "=SUMIF(R3C8:R" & lastRow & "C8,""" & CritLastCol & """,R3C10:R" & lastRow & "C" & lastCol & ")" 

通知周邊CritLastCol

+0

My CritLastCol隨着每行而改變。所以,當我添加額外的雙引號時,它會在我想要的列中提取值,但是當我自動填充它時,它會保留該值,但我希望它將下一列的critera取而代之。 – 2014-10-03 14:12:15

0

好額外的雙引號,我想出了一個辦法做到這一點......而是自動填充的,我用了一個循環從我的數據結束開始並繼續工作。

Sub SumBydimcode() 
Dim lastCol As Integer 
Dim CritLastCol As String 
lastCol = Cells(3 & Columns.Count).End(xlToLeft).Column 
lastRow = Range("A" & Rows.Count).End(xlUp).Row 
NewLastRow = Range("I" & Rows.Count).End(xlUp).Row 
NewFirstRow = lastRow + 7 


S = ActiveCell.Row 
If S > NewLastRow - NewFirstRow Then 
For S = ActiveCell.Row To NewFirstRow Step -1 

    CritLastCol = ActiveCell.End(xlToLeft).Value 
    ActiveCell.FormulaR1C1 = "=SUMIF(R3C8:R" & lastRow & "C8,""" & CritLastCol & """,R3C10:R" & lastRow & "C" & lastCol & ")" 

ActiveCell.Offset(-1, 0).Select 

Next S 
End If   

End Sub