2

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

2 回答 2

6

FormulaR1C1是公式的写法。

Formula指在A1中写一个公式,如=B1+C1

要使用符号编写相同的公式R1C1,您将编写=RC[1] + RC[2]. 此外,要=B2+C2在 A1 中写入,请写入=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 
于 2012-10-29T14:28:41.003 回答
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""" & ")"
于 2012-10-29T14:32:31.297 回答