#值! 编写公式时出错

我有一段代码循环访问一列,并将公式插入到该列的每个单元格中。 代码运行,唯一的问题是每个单元格的公式插入到显示#Value! 有谁知道如何解决这一问题? 下面是这个问题的一段代码:

Dim j As Long 'Loop down the rows in mainfile For j = 2 To lastFullRow2 ' Make each argument a string, then concatenate it all all into large string Dim firstArgument As String firstArgument = "ws_multidax.Range(" & valuecolumnLetter & "2:" & valuecolumnLetter & lastFullRow1 & ")" Dim secondArgument As String secondArgument = "ws_multidax.Range(" & parameter1columnLetter & "2:" & parameter1columnLetter & lastFullRow1 & ")" Dim thirdArgument As String thirdArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")" Dim fourthArgument As String fourthArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")" Dim condition3 As String condition3 = "ws_mainfile.Range(" & "D2:" & D & j & ")" Dim patid1 As String patid1 = "ws_multidax.Range(" & "D2:" & D & lastFullRow2 & ")" With ws_mainfile Dim commandstring As String 'The formula we want is a concatenated string commandstring = "{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}" 'Insert the formula into each cell as the loop goes down the rows ws_mainfile.Range("AN" & j).Formula = Eval(commandstring) 'ws_mainfile.Range("AN" & j).Formula = commandstring End With Next j 

价值! 当我用Eval(命令string)运行这个命令时,它会被放入单元格中。 当我用公式=命令string运行这个行时,公式会被放到每个单元格中,但是它不能解决。

你的代码有两个问题:

  1. 你手动放入一个数组公式的花括号,不要这样做
  2. 你正在把数组公式作为一个数组公式

所以要更正,请执行以下操作:

 '1. Change this line: commandstring = "{=INDEX(....)}" 'And simply remove the curly braces {} from its beginning and end commandstring = "=INDEX(....)" '2. Change this line: ws_mainfile.Range("AN" & j).Formula = Eval(commandstring) 'To use the .FormulaArray property instead of just .Formula: ws_mainfile.Range("AN" & j).FormulaArray = commandstring 

你在正确的轨道上。 没有必要使用eval函数,因为您已经在代码中构build了一个string公式。 问题在于你用大括号把它包围起来,就像你input了文字一样。

试试这个:

 commandstring = "=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))" 'Insert the formula into each cell as the loop goes down the rows ws_mainfile.Range("AN" & j).Formula = commandstring