2017-07-27 47 views
0

嗨我正在編寫一個基於標準的數據求和代碼。下面的代碼工作完美,但它不會返回值。該代碼適用於像這樣的(= SUMIF($B$1:$DC$1,p,B2:DD2)的Excel。原因是標準P需要雙quotation.how到雙引號添加到P任何建議,將不勝感激VBA:Sumif函數不能正常工作

Sub ashok() 
Dim LR As Long 
Dim Rg, Rg1 As Range 

       ActiveSheet.Range("a1").Select 
       LR = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 
       ActiveCell.Columns("A:A").EntireColumn.Select 
       Selection.NumberFormat = "0" 
       ActiveSheet.Range("a1").Select 
       Set Rg = Range("b1", ActiveSheet.Range("A1").End(xlToRight)) 
       Set Rg1 = Range("b2", ActiveSheet.Range("A2").End(xlToRight)) 
       Range("a1").End(xlToRight).Select 

       With ActiveCell.Offset(1, 1).Resize(LR) 
       .Formula = "= SumIf(" & Rg.Address(True, True) & "," & "P" & "," & Rg1.Address(False, False) & ")" 
       End With 
End Sub 
+2

[在VBA放置在雙引號內的String]的可能的複製(https://stackoverflow.com/questions/42960548 /放置雙引號內的字符串在VBA) –

回答

5

回答你的問題是使用Chr(34)

.Formula = "= SumIf(" & Rg.Address(True, True) & "," & Chr(34) & "P" & Chr(34) & "," & Rg1.Address(False, False) & ")" 

然而,你有太多(不必要,應該遠離)使用SelectActiveSheet,ActiveCellSelection

,如果你使用完全合格的對象代碼如何能看一個例子:

With Sheets("Sheet3") ' <-- replace with your sheet's name 

    LR = .Cells(.Rows.Count, "A").End(xlUp).Row 

    .Columns("A:A").EntireColumn.NumberFormat = "0" 

    Set Rg = .Range("B1", .Range("A1").End(xlToRight)) '<-- NOT SURE this make sense ! 
    Set Rg1 = .Range("B2", .Range("A2").End(xlToRight)) '<-- NOT SURE this make sense ! 

    ' etc. etc. 

End With ' closing the With 
+0

20恭喜20K :) –

+1

@ASH大聲笑,謝謝:)現在我還有一件事,追逐VBA和Excel VBA的黃金徽章 –

+1

是的,那裏有很多問題要在現場關閉:P –