使用VBA在单元格中输入公式

时间:2018-08-02 17:55:43

标签: excel vba

我正在尝试在表格中放置一个公式。

cells(2,i).formulaR1C1行上我有一个错误1004,尽管我记录了该公式,该公式有效并与记录的相同。

“ CLEVES 1”至“ CLEVES 5”是表中的标题。要测试此代码,请创建一个表,其标题为CLEVES 1至CLEVES 5。

enter image description here

Sub formula()

    Dim i As Long, ce As String

    For i = 1 To 10
        ce = CStr(Cells(1, i).Value)
        Cells(2, i).FormulaR1C1 = "=IF(OR(MID([@[CLEVES 1]],1,2)=""" & ce & """,MID([@[CLEVES 2]],1,2)=""" & ce & """,MID([@[CLEVES 3]],1,2)=""" & ce & """,MID([@[CLEVES 4]],1,2)=""" & ce & """,MID([@[CLEVES 5]],1,2)=""" & ce & """),& ce &,"""")"
    Next

End Sub

1 个答案:

答案 0 :(得分:0)

您需要将工作表名称设置为公式

  

= IF(OR(MID([“&sheetName&”!@ [CLEVES 1]],1,2)=“”“

例如。

我在Sheet2上创建了表格,并且工作正常:

 Sub formula()
    Dim i As Long
    Dim ce As String
    Dim formulaString As String
    Dim ws As Worksheet
    Dim sheetName As String

    Set ws = Sheets("sheet2")

    sheetName = "Sheet2"

    For i = 7 To 17
            ce = CStr(Cells(1, i).Value)
            formulaString = Cells(2, i).FormulaR1C1 = "=IF(OR(MID([" & sheetName & "!@[CLEVES 1]],1,2)=""" _
            & ce & """,MID([" & sheetName & "!@[CLEVES 2]],1,2)=""" & ce & """,MID([" & sheetName & "!@[CLEVES 3]],1,2)=""" _
            & ce & """,MID([" & sheetName & "!@[CLEVES 4]],1,2)=""" & ce & """,MID([" & sheetName & "!@[CLEVES 5]],1,2)=""" & ce & """),& ce &,"""")"
            ws.Cells(2, i).FormulaR1C1 = formulaString
    Next
End Sub