2017-09-14 174 views
1

首先,我试图查看使用VBA添加公式的所有其他示例,并且我认为我已尝试在此代码中应用所有答案在Excel中使用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 

但尽管如此,它给了我这个是烦人的错误,我无法解释 enter image description here

如果我改变我行

Wksht.Cells(i, 18) = "'IFERROR(VLOOKUP(A" & i & ";" & Wksht.Cells(1, 18) & "!$A:$A;1;FALSE);" & Chr(34) & "MISSING" & Chr(34) & ")" 

然后时I g等没有错误,并添加了正确的公式,虽然作为文本字符串

什么是错的,因为它不会添加什么对我来说看起来像一个有效的公式?

// V

+2

通过VBA插入时,必须使用英文版公式。所以'''应该是','。 – YowE3K

+0

您应该在'Wksht.Cells(x,x)'后面使用'.Formula'或'.Formulalocal'或'.Value'或'.Text'' – Tibo

回答

2

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) & ")" 
+0

谢谢! @YowE3K这就是为什么我也喜欢SO。 现在我已经学到了一些我以前不知道的新东西, – Verakso

0

写公式,因为它应该在Excel中,选择它并运行以下代码:

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 

它应该打印它应该是。

0

我相信你的代码给出这个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)确实包含您尝试解决的工作表的名称。如果这个单元格是空白的,你将会收到前面提到的错误。