以公式forms评估string
作为一段较长的代码的一部分,我已经把一个公式变成了一个string。 现在我想下一列,并将该公式放入每个单元格中。 我遇到了VBA代码评估我的string作为公式的问题。 当我尝试像这样评估公式时,在我尝试评估的行处出现types不匹配错误。 以下是我遇到的问题:
Dim commandstring As String commandstring = [{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}]
我读了方括号围绕公式将评估,但我不能得到它的工作。 任何帮助表示赞赏,谢谢!
循环并将公式放入单元格公式中。 这里的string是固定的。
commandstring = "{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}" Dim lRow As Long Dim ws As Excel.Worksheet Set ws = ActiveWorkbook.Sheets("Sheet1") lRow = 1 'Loop through and put the formula in each cell Do While lRow <= ws.UsedRange.Rows.count ws.Range("B" & lRow).Formula = "{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}" lRow = lRow + 1 Loop
或者如果你真的想在一个stringvariables中使用它。
ws.Range("B" & lRow).Formula = commandstring
试试这个以string作为公式的小函数:
Function Eval(Ref As String) Application.Volatile Eval = Evaluate(Ref) End Function
调用这个函数:
Dim commandstring As String commandstring = "{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}" commandstring = Eval(commandstring)