字符串中的Excel VBA公式

时间:2016-10-06 14:07:59

标签: excel vba excel-vba macros excel-formula

尝试将公式放入字符串中并且无法使其正常工作。有人可以帮我把它变成一个字符串吗?我知道我需要做""&""在某些地方,我只是不知道在哪里......

Dim form As String
form = =IFERROR(GETPIVOTDATA("[Measures].[Sum of Amount]",Pivot!$A$3,"[qAllData].[Year]","[qAllData].[Year].&[2.016E3]","[qAllData].[Month Name]","[qAllData].[Month Name].&["&$B9&"]","[qAllData].[PRODUCT_CODE]","[qAllData].[PRODUCT_CODE].&["&C$3&"]","[qAllData].[Product Name]","[qAllData].[Product Name].&["&C$4&"]")-C8-C7-C6-C5,0)

2 个答案:

答案 0 :(得分:2)

如果您的表格是电子表格中的详细信息,但您想将其与VBA一起插入,那么只需:

Dim form As String
form = "=IFERROR(GETPIVOTDATA(""[Measures].[Sum of Amount]"",Pivot!$A$3,""[qAllData].[Year]"",""[qAllData].[Year].&[2.016E3]"",""[qAllData].[Month Name]"",""[qAllData].[Month Name].&[""&$B9&""]"",""[qAllData].[PRODUCT_CODE]"",""[qAllData].[PRODUCT_CODE].&[""&C$3&""]"",""[qAllData].[Product Name]"",""[qAllData].[Product Name].&[""&C$4&""]"")-C8-C7-C6-C5,0)"

这只是将每个"替换为""并将整个内容包装在引号中。 VBA接受它作为一个有效的公式,但我不确定这是你真正想要的。

答案 1 :(得分:1)

如果它是一个有效的公式而你只想把它作为String变量,你需要做的就是用双引号(")开始和结束它然后加倍所有内部引号(""),如下:

form = "=IFERROR(GETPIVOTDATA(""[Measures].[Sum of Amount]"",Pivot!$A$3,""[qAllData].[Year]"",""[qAllData].[Year].&[2.016E3]"",""[qAllData].[Month Name]"",""[qAllData].[Month Name].&[""&$B9&""]"",""[qAllData].[PRODUCT_CODE]"",""[qAllData].[PRODUCT_CODE].&[""&C$3&""]"",""[qAllData].[Product Name]"",""[qAllData].[Product Name].&[""&C$4&""]"")-C8-C7-C6-C5,0)"