VBA基于另一个variables创build公式
我想在Excel中使用vba创build下面的公式
=SUM(COUNTIF(E7,"Vac")+ COUNTIF(E7,"LWOP")+COUNTIF(R7,"Vac")+ COUNTIF(R7,"LWOP"))
但是E7和R7会根据另一个名为rCell.address
variables进行rCell.address
下面是我在macros中的代码,它给出了一个错误:
Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ", "VAC"" & "))"
目前的macros是:
Sub Find() Dim strdate As String Dim rCell As Range Dim lReply As Long With Worksheets("Sheet1") strdate = .Range("a1").Value End With If strdate = "False" Then Exit Sub strdate = Format(strdate, "Short Date") On Error Resume Next Set rCell = Cells.Find(What:=CDate(strdate), After:=Range("A1"), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False) On Error GoTo 0 If rCell Is Nothing Then lReply = MsgBox("Date cannot be found. Try Again", vbYesNo) If lReply = vbYes Then Run "FindDate": End If Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ",VAC" & "))" End Sub
我假设你的错误出现在这行代码: Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ",VAC" & "))"
。
你应该改变这一行
Range("a8").Formula = "=SUM(COUNTIF(" & rCell.Address & "," & Chr(34) & "Vac" & Chr(34) & ")+ COUNTIF(" & rCell.Address & "," & Chr(34) & "LWOP" & Chr(34) & ")+COUNTIF(" & rCell.Offset(0, 13).Address & "," & Chr(34) & "Vac" & Chr(34) & ")+ COUNTIF(" & rCell.Offset(0, 13).Address & "," & Chr(34) & "LWOP" & Chr(34) & "))"
感谢KS Sheon,更新了更好的答案
Range("a8").Formula = "=SUM(COUNTIF(" & rCell.Address & ",""Vac"")+ COUNTIF(" & rCell.Address & ",""LWOP"")+COUNTIF(" & rCell.Offset(0, 13).Address & ",""Vac"")+ COUNTIF(" & rCell.Offset(0, 13).Address & ",""LWOP""))"
SUMIF
在这方面是错误的。
Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ",VAC" & "))"
你应该像这样使用SUMIF
Range("a8").Formula =SUMIF(B2:B25,">5")