简体   繁体   English

从 Excel 宏向单元格添加公式

[英]Adding Formula to Cell from Excel Macro

I have a macro button in worksheet 2 and want it to put a formula into a column of worksheet 1. For example I can do a simple sum formula such as:我在工作表 2 中有一个宏按钮,并希望它将公式放入工作表 1 的列中。例如,我可以执行一个简单的求和公式,例如:

Sheets("worksheet1").Range("I:I") = "=SUM(M:M)"

This works but when I try and do it with the actual more complicated formula I want it will not work.这有效,但是当我尝试使用实际更复杂的公式进行操作时,我希望它不起作用。 Why is this?为什么是这样?

Sheets("worksheet1").Range("I:I") = "=IF(ISNUMBER(SEARCH("*567*",B:B)),"INSTOCK","")"

Writing a double quote like you did makes VBA think you ended your string after just writing "=IF(ISNUMBER(SEARCH(" . In fact, this code will error out. You'll need to double-up your quotes. A great way to understand what you are writing would be to use Debug.Print first:像你一样写一个双引号会让 VBA 认为你在写完"=IF(ISNUMBER(SEARCH("之后就结束了你的字符串。事实上,这段代码会出错。你需要把你的引号加倍。一个很好的方法要了解您正在编写的内容,请先使用Debug.Print

Debug.Print "=IF(ISNUMBER(SEARCH(""*567*"",B:B)),""INSTOCK"","""")"

So this will work:所以这将起作用:

Sheets("worksheet1").Range("I:I") = "=IF(ISNUMBER(SEARCH(""*567*"",B:B)),""INSTOCK"","""")"

Note: since you are using whole column references, this is going to be heavy on your calculation!注意:由于您使用的是整列引用,这将对您的计算产生很大影响!

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

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