简体   繁体   English

使用VBA在一个单元格中插入公式

[英]Insert formula in one cell using VBA

I know this topic was already asked and I tried to copy on how to insert a formula in one cell, however, I got an error in my vba code. 我知道已经询问了这个主题,我尝试复制如何在一个单元格中插入公式,但是,我的vba代码出现错误。

在此处输入图片说明

Here is my code: 这是我的代码:

ws.Range("C9").Formula = "=CountIf(wsRD.Range(C & Rows.count).End(xlUp).Row, ""Event"")"   'CountIf(wsRD.Range("C" & Rows.count).End(xlUp).Row, "Event") 'count(Search("Event", wsRD.Range("C" & Rows.count).End(xlUp).Row, 1))

I need to insert a formula in ws.Range("C9"), in which, it summarizes the count of the cell that have a value of "Event" in wsRD.Range("C" & Rows.count).End(xlUp).Row. 我需要在ws.Range(“ C9”)中插入一个公式,其中它汇总了wsRD.Range(“ C”&Rows.count).End()中值为“ Event”的单元格的计数xlUp)。 May I know what's the problem in my code? 我可以知道代码中的问题吗? Appreciate your help. 感谢您的帮助。

Thank you. 谢谢。

You could get rid of the LRow variable and just drop it in your equation if you wanted to. 如果需要,可以摆脱LRow变量,而只需将其放在等式中。

Dim LRow as Long
LRow = ws.Range("C" & ws.Rows.Count).End(xlUp).Row

ws.Range("C9").Formula = "=COUNTIF(C10:C" & LRow & ", ""Event"")"

I'm sure this could be the correct answer 我确定这可能是正确的答案

ws.Select
LRow = ws.Range("C" & Rows.Count).End(xlUp).Row

Range("C9").FormulaLocal = "=COUNTIF(C10:C" & LRow & ";""Event"")"

So basically, I used FormulaLocal to write the formula the same way I write it in Excel, then, because the formula must be a big String, I separated it in 2 strings, put the value LRow, and used & & to concatenate 因此,基本上,我使用FormulaLocal编写公式的方式与在Excel中编写公式的方式相同,然后,由于公式必须为大字符串,因此将其分成2个字符串,放入值LRow,并使用&&进行连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM