我在函数中输入以下公式。
dim minfee, feetier3, feetier4, feetier5, bpspread1, bpsread2, bpspread3 as double
call insformulaincell("=IF(K2 = 100, ""#NA"", IF(K2 <" & minfee & "," & feetier3 & ",IF(K2<" & feetier4 & ",K2+ " & bpspread1 & ",IF(K2<" & feetier5 & ",K2+ " & bpspread2 & ",K2+ " & bpspread3 & "))))")
'all the function does is paste the formula into a cell
'How would I format the formula so that it can be stored as a single string?
'Ex:
dim sFormula as string
sformula = ""=IF(K2 = 100, ""#NA"", IF(K2 <" & minfee & "," & feetier3 & ",IF(K2<" & feetier4 & ",K2+ " & bpspread1 & ",IF(K2<" & feetier5 & ",K2+ " & bpspread2 & ",K2+ " & bpspread3 & "))))""
call insformulaincell(sFormula)
主要问题是诸如minfee之类的变量不会引用其实际值,而是显示实际的字符串变量名称。
例如:“ ... If(K2 <”&minfee&“,” ...) 相对于 “ ... If(K2 <1)...”'假设minfee = 1
答案 0 :(得分:2)
在VBA中,"
用作字符串文字的分隔符,如下所示:
Dim foo As String
foo = "some string"
如果您的字符串文字需要包含"
双引号,则需要通过在字符串定界符之间将它们加倍 ,以转义:
foo = """some string"""
打印以上内容将产生"some string"
,其中包括双引号。
因此,您要做需要remove the leading & trailing double quotes。
sformula = "=IF(K2 = 100, ""#NA"", IF(K2 <" & minfee & "," & feetier3 & ",IF(K2<" & feetier4 & ",K2+ " & bpspread1 & ",IF(K2<" & feetier5 & ",K2+ " & bpspread2 & ",K2+ " & bpspread3 & "))))"
简而言之,它是以下文字的串联:
"=IF(K2 = 100, ""#NA"", IF(K2 <"
(注:"#NA"
是IMO的一个坏主意。使用NA()
函数产生实际的工作表错误,而不是看起来的字符串值就像一个)","
",IF(K2<"
",K2+ "
",IF(K2<"
",K2+ "
",K2+ "
"))))"
哪个对我合适。
可以说,这种级联令人讨厌。定制的StringFormat函数可以通过抽象化串联来帮助缓解这种情况:
sFormula = StringFormat("=IF(K2=100, ""#NA"", IF(K2<{0},{1},IF(K2<{2},K2+{3},IF(K2<{4},K2+{5},K2+{6}", _
minfee, feetier3, feetier4, bpspread1, feetier5, bpspread2, bpspread3)