简体   繁体   English

有没有一种方法可以使用VBA for Excel将公式输出到Excel工作表中的特定单元格?

[英]Is there a way to use VBA for Excel to output a formula to a specific cell in an Excel worksheet?

I am fairly new at programming. 我是编程新手。 I feel like this should be a simple fix but I cannot find anything that works. 我觉得这应该是一个简单的解决方法,但我找不到任何有效的方法。 I am trying to use a Select Case structure to write a different formula to a cell depending on the selected case. 我正在尝试使用“ Select Case结构,根据所选的大小写将不同的公式写入单元格。 If I type: 如果输入:

Sheet1.Range("g10").Value = "=IF(SUM(F10)>0,SUM((F10-15)),"")" 

I get an error: 我收到一个错误:

Run-time error '1004' 运行时错误'1004'
Application-defined or object-defined error. 应用程序定义或对象定义的错误。

I can get it to work if I include spaces like so: 如果包含如下所示的空格,则可以使其正常工作:

Sheet1.Range("g10").Value = " =IF(SUM(F10)>0,SUM((F10-15)),"") "

but then Excel puts it into the cell like text, not as a formula (it doesn't do anything). 但是Excel会将其像文本一样放入单元格中,而不是作为公式(它不会执行任何操作)。

I have tried a few different methods but have run into the same issue. 我尝试了几种不同的方法,但是遇到了相同的问题。 Is it possible to do this? 是否有可能做到这一点?

I apologize if this has been asked and answered, but I wasn't able to find anyone referencing this specific problem. 如果有人提出并回答了这个问题,我深表歉意,但是我找不到任何人引用此特定问题。

Wrong property. 属性错误。 You need .formula not .value 您需要.formula而不是.value

worksheets("sheet1").range("g10").formula = "=IF(SUM(F10)>0,SUM((F10-15)),"")"

You don't need to sum a single cell ie SUM(F10) Also SUM((F10-15)) is the same as F10-15 . 您不需要求和单个单元格,即SUM(F10)而且SUM((F10-15))F10-15相同。

Try this: Sheet1.Range("g10").Formula = "=IF(F10>0,F10-15,"""")" Also note, you needed to double the double quotes towards the end. 尝试以下操作: Sheet1.Range("g10").Formula = "=IF(F10>0,F10-15,"""")"另外请注意,您需要在结尾处将双引号加倍。

Note, you can do this on a range too like this: 注意,您也可以在如下范围内执行此操作:

Sheet1.Range("g10:g20").Formula = "=IF(F10>0,F10-15,"""")" and it is smart enough to increment the references for you for the 10 cells. Sheet1.Range("g10:g20").Formula = "=IF(F10>0,F10-15,"""")" ,它足够聪明,可以为10个单元格增加引用。

You should be able to type out the formula and then turn on the Macro Recorder and double-click on the cell with the forums, then turn off the Macro recorder and examine your code. 您应该能够键入公式,然后打开Macro Recorder,然后双击带有论坛的单元格,然后关闭Macro Recorder并检查您的代码。 That should give you what you want. 那应该给你你想要的。

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

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