通过Access VBA将公式写入Excel

KSM*_*KSM 2 excel ms-access vba 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 
Run Code Online (Sandbox Code Playgroud)

Sco*_*man 6

FormulaR1C1 是如何编写公式的方法.

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

要使用R1C1表示法编写相同的公式,您可以编写=RC[1] + RC[2].此外,要写入=B2+C2A1,请写入=R[1]C[1] + R[1]C[2]- >,这样您就可以看到偏移了希望公式返回值的列和行.

你想在代码中做什么是偏移公式的位置,而不是它的计算方式,所以你应该这样写:

.ActiveCell.Offset(,1).Formula = strExcel
Run Code Online (Sandbox Code Playgroud)

实际上,你应该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 
Run Code Online (Sandbox Code Playgroud)