简体   繁体   中英

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:

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:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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