不能使用宏vba excel将countifs公式设置为单元格

时间:2016-05-24 03:10:33

标签: excel-vba excel-formula vba excel

我需要编写一个将countifs公式输入到单元格

的宏

我的错误是什么?

Dim ReferSheet As String
ReferSheet = ActiveSheet.Name

ActiveCell.Offset(RowOffSet:=0, ColumnOffset:=1).Select
ActiveCell.Formula = "=Application.WorksheetFunction.CountIfs(Worksheets(ReferSheet).Range("D8:D1103"), " >= " & Worksheets("Display").Range("C9"), Worksheets(ReferSheet).Range("D8:D1103"), " <= " & Worksheets("Display").Range("H9"), Worksheets(ReferSheet).Range("L8:L1103"), " > " & 0)"

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

  1. 我构建了一个中间字符串,并使用debug.print作为检查字符串的方法,以确保它符合您的要求。
  2. 一旦确定自己拥有所需内容,就可以消除中间字符串和debug.print语句,并在ActiveCell.Formula
  3. 的分配中直接使用公式

    代码......

    Sub t1()
    Dim ReferSheet As String
    Dim formulaStr As String
    
        ReferSheet = ActiveSheet.Name
    
        ActiveCell.Offset(RowOffSet:=0, ColumnOffset:=1).Select
        formulaStr = "=CountIfs($D$8:$D$1103," & """>=""" & " & $C$9," & "$D$8:$D$1103," & _
                         """<=""" & " & $H$9," & "$L$8:$L$1103," & """>0""" & ")"
        Debug.Print formulaStr
        ActiveCell.Formula = formulaStr
    End Sub
    

    结果......

    =COUNTIFS($D$8:$D$1103,">=" & $C$9,$D$8:$D$1103,"<=" & $H$9,$L$8:$L$1103,">0")