【问题标题】:Debug countif and autofill in excel VBA, criteria doesn't work在excel VBA中调试countif和自动填充,条件不起作用
【发布时间】:2020-01-02 04:03:24
【问题描述】:

我需要一个函数来计算 J 列中每个项目的数量并在 K 列显示结果。但是我在下面显示的这段代码一直说标准部分 RC[-2] 是错误的。在 countif 函数之后,我需要它能够自动填充给定的任何行,以便我也可以将此代码应用于其他文件。

我使用宏生成一些代码来启动。也可以早点尝试: paste_countPTD = Worksheetfunction.CountIf(paste_conPTD,RC[-2]).

标准部分似乎有误。

Dim paste_conPTD As Range
Set paste_conYTD = Range("J2:J" & Range("A" & Rows.Count).End(xlUp).Row)

Range("K1").Select
ActiveCell.FormulaR1C1 = "Count_PTD"
Range("K2").Worksheetfunction.countif(paste_conPTD,RC[-2])

感谢任何使此代码有效的建议。对列进行计数并自动填充公式。

【问题讨论】:

    标签: excel vba range criteria countif


    【解决方案1】:

    如果您想要单元格中的实际公式,请尝试此操作。 将 paste_conPTD 调暗为范围

        Set paste_conYTD = Range("J2:J" & Range("A" & Rows.Count).End(xlUp).Row)
    
        Range("K1").Value = "Count_PTD"
        paste_conYTD.Offset(, 1).FormulaR1C1 = "=COUNTIF(" & paste_conYTD.Address(ReferenceStyle:=xlR1C1) & ",RC[-2])"
    

    【讨论】:

      【解决方案2】:

      你可以试试这个代码

      Dim paste_conPTD As Range
      Set paste_conYTD = Range("J2:J" & Range("A" & Rows.Count).End(xlUp).Row)
      
      Range("K1") = "Count_PTD"
      
      Dim iRng as Range   
      
      For each iRng in paste_conPTD
      
          iRng.Offset(0,1) = Worksheetfunction.Countif(paste_conPTD, iRng)
      
      Next iRng
      

      为了给您一些注释,我们需要迭代 paste_conYTD 范围内的每个单元格,这就是 iRng 的来源。我们不能像 paste_conYTD = <some formula> 那样告诉 Excel 和假设 Excel 知道我们希望它使用公式计算每个单元格。 Excel迭代有几种方式,我们可以根据场景选择最容易应用的一种。

      • For each ... in ... Next

      https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/for-eachnext-statement

      • For ... Next

      https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/fornext-statement

      • Do... Loop

      https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/doloop-statement

      • While... Wend

      https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/whilewend-statement

      【讨论】:

        猜你喜欢
        • 2017-07-22
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-07
        • 1970-01-01
        相关资源
        最近更新 更多