通过Access VBA将公式写入Excel

我想在“A1”中插入一些文本“ABC”,并在“B1”中插入一个if语句。 但是,我只得到插入第一个条目“ABC”,然后在FormulaR1C2 "Object doesn't support this property or method" 。 我不确定我是否正确使用R1C2 。 我假设它代表第1列第2列,有人可以帮我。

 Dim Excel_App As Object Dim strExcel As String Set Excel_App = CreateObject("Excel.Application") Excel_App.Visible = True Excel_App.Workbooks.Add With Excel_App .Range("A:B").EntireRow.ColumnWidth = 25 .Range("A2").EntireRow.Font.FontStyle = "Bold" .ActiveCell.FormulaR1C1 = "ABC" strExcel = "=IF(A1 = """"," & """EMPTY""" & "," & """FILLED""" & ") " .ActiveCell.FormulaR1C2 = strExcel End With 

FormulaR1C1是如何写公式的方法。

Formula是指在A1中写出一个公式=B1+C1

要使用R1C1表示法编写相同的公式,可以写为=RC[1] + RC[2] 。 此外,在A1中写入=B2+C2写这个=R[1]C[1] + R[1]C[2] – >所以你可以看到你正在抵消你想公式返回值的列和行从。

你想要在你的代码中做的是抵消公式将被放置的地方,而不是如何计算,所以你应该写这个:

 .ActiveCell.Offset(,1).Formula = strExcel 

实际上,你应该完全摆脱ActiveCell ,除非你绝对需要它。

我会写这样的代码,以更好,更准确的执行:

 Dim Excel_App As Object Dim strExcel As String Dim wkb as Object, wks as Object Set Excel_App = CreateObject("Excel.Application") Excel_App.Visible = True Set wkb = Excel_App.Workbooks.Add Set wks = wkb.Sheets(1) 'assumes you want first sheet, can modify for sheet index or name With wks .Range("A:B").EntireRow.ColumnWidth = 25 'I think this will actually set every row to 25, is that what you want? .Range("A2").EntireRow.Font.FontStyle = "Bold" .Range("A1").Value = "ABC" 'don't need to write Value, but just to show you the property strExcel = "=IF(A1 = """"," & """EMPTY""" & "," & """FILLED""" & ") " .Range("B1").Formula = strExcel End With 

FormulaR1C1是返回用R1C1公式表示的单元格公式的属性。

您需要通过使用Workbook.WorkSheet.Range语法来引用cells

所以首先你需要指定你正在工作的工作簿,在你的情况下是由Excel_App.Workbooks.Add语句添加的工作簿。 您的新工作簿被自动命名为“Book1”,并通过“Sheetn”自动添加名为“Sheet1”的默认工作表数量,其中n是默认页数。

所以你是最后的代码写入该行是

 Excel_App.Workbooks(1).Worksheets("Sheet1").Cells(1, 1) = "ABC" Excel_App.Workbooks(1).Worksheets("Sheet1").Cells(1, 2).Formula = "=IF(A1 = """"," & """EMPTY""" & "," & """FILLED""" & ")"