通过Access VBA将公式写入Excel

时间:2012-10-29 14:07:47

标签: excel vba ms-access excel-vba

我想在“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 

2 个答案:

答案 0 :(得分:5)

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 

答案 1 :(得分:0)

FormulaR1C1是一个属性,它返回以R1C1公式样式表示的单元格的公式。

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

首先,您需要指定您正在使用的工作簿,在您的情况下,该工作簿是由语句Excel_App.Workbooks.Add添加的工作簿。您的新工作簿会自动命名为“Book1”,并自动添加名为“Sheet1”到“Sheetn”的默认工作表数量,其中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""" & ")"