调试计数如果在 excel VBA 中自动填充,条件不起作用



我将需要一个函数来计算 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])

我很感激任何使此代码工作的建议。对列进行计数并自动填充公式。

你可以试试这段代码

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://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/for-eachnext-statement

  • For ... Next

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

  • Do... Loop

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

  • While... Wend

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

如果您想在单元格中使用实际公式,请尝试此操作。 暗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])"

最新更新