在Excel中使用VBA插入公式不起作用
首先,我试图看看使用VBA添加公式的所有其他示例,并且我想我已经尝试在此代码中应用所有答案
Sub AddFormulas(SheetName As String) Dim i As Integer 'Switch worksheet Set Wksht = ThisWorkbook.Worksheets(SheetName) Wksht.Activate Application.Calculation = xlCalculationManual i = 2 While Not IsEmpty(Cells(i, 1)) Wksht.Cells(i, 18).Formula = "=IFERROR(VLOOKUP(A" & i & ";" & Wksht.Cells(1, 18) & "!$A:$A;1;FALSE);" & Chr(34) & "MISSING" & Chr(34) & ")" i = i + 1 Wend Application.Calculation = xlCalculationAutomatic End Sub
但是,这仍然给了我这个无法解释的错误
如果我改变我的路线
Wksht.Cells(i, 18) = "'IFERROR(VLOOKUP(A" & i & ";" & Wksht.Cells(1, 18) & "!$A:$A;1;FALSE);" & Chr(34) & "MISSING" & Chr(34) & ")"
然后我得到没有错误,并添加正确的公式,虽然作为一个文本string
什么是错误的,因为它不会增加我看起来像一个有效的公式?
// V
Formula
属性要求公式用英文写成,即英文函数名称(这里不是问题)和逗号分隔符而不是分号。
所以你的陈述应该是:
Wksht.Cells(i, 18).Formula = "=IFERROR(VLOOKUP(A" & i & "," & Wksht.Cells(1, 18) & "!$A:$A,1,FALSE)," & Chr(34) & "MISSING" & Chr(34) & ")"
如果你不介意有“便携性”的问题,你也可以使用FormulaLocal
属性,即
Wksht.Cells(i, 18).FormulaLocal = "=IFERROR(VLOOKUP(A" & i & ";" & Wksht.Cells(1, 18) & "!$A:$A;1;FALSE);" & Chr(34) & "MISSING" & Chr(34) & ")"
写入公式,因为它应该是在Excel中,select它并运行以下代码:
Public Sub PrintMeUsefulFormula() Dim strFormula As String Dim strParenth As String strParenth = """" strFormula = Selection.Formula strFormula = Replace(strFormula, """", """""") strFormula = strParenth & strFormula & strParenth Debug.Print strFormula End Sub
它应该打印它应该是。
我相信你的代码是错误的, Wksht.Cells(1, 18)
这行Wksht.Cells(i, 18).Formula = "=IFERROR(VLOOKUP(A" & i & ";" & Wksht.Cells(1, 18) & "!$A:$A;1;FALSE);" & Chr(34) & "MISSING" & Chr(34) & ")"
Wksht.Cells(1, 18)
部分行Wksht.Cells(i, 18).Formula = "=IFERROR(VLOOKUP(A" & i & ";" & Wksht.Cells(1, 18) & "!$A:$A;1;FALSE);" & Chr(34) & "MISSING" & Chr(34) & ")"
确保Wksht.Cells(1, 18)
确实包含您正在尝试解决的工作表的名称。 如果这个单元格是空的,你将会收到前面提到的错误。