Adding Formula to Cell from Excel Macro

余生长醉 提交于 2020-01-25 06:43:08

问题


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","")"

回答1:


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!



来源:https://stackoverflow.com/questions/59785221/adding-formula-to-cell-from-excel-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!