VBA根据另一个变量创建公式

时间:2016-03-02 02:24:01

标签: excel vba excel-vba

我正在尝试使用excel

中的vba创建下面的公式
=SUM(COUNTIF(E7,"Vac")+ COUNTIF(E7,"LWOP")+COUNTIF(R7,"Vac")+ COUNTIF(R7,"LWOP"))

但是E7和R7会根据另一个名为rCell.address

的变量而改变

下面是我在宏中的代码,它给出了一个错误:

Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ", "VAC"" & "))"

当前的宏是:

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

2 个答案:

答案 0 :(得分:3)

我假设您的错误出现在这行代码中: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""))"

答案 1 :(得分:1)

SUMIF在这种情况下是错误的。

Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ",VAC" & "))"

你应该像这样使用SUMIF

Range("a8").Formula =SUMIF(B2:B25,">5")