gpt4 book ai didi

vba - 通过Access VBA将公式写入Excel

转载 作者:行者123 更新时间:2023-12-03 00:32:10 27 4
gpt4 key购买 nike

我想在“A1”中插入一些文本“ABC”,并在“B1”中的以下单元格中插入 if 语句。但是,我只插入了第一个条目“ABC”,然后在 FormulaR1C2“对象不支持此属性或方法” 处出现错误。我不确定我是否正确使用了 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 是公式的编写方法。

公式是指在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

关于vba - 通过Access VBA将公式写入Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123230/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com