2017-09-14 181 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)確實包含您嘗試解決的工作表的名稱。如果這個單元格是空白的,你將會收到前面提到的錯誤。