Python xlwings复制粘贴公式与相对单元格引用



我在单元格 A1 中有一个公式,它"=C1+$D$1".我想使用 xlwings 将此公式复制粘贴到 A3 中(保留相对单元格引用(。我希望单元格 A3 中粘贴的公式是"=C3+$D$1"而不是"=C1+$D$1".

是否有一个标志或函数可以根据我们粘贴到的范围调整公式?如果没有,我想最好的解决方案是在粘贴之前处理公式本身?

rng_to_paste = ws.range('A1').options(ndim=1).formula
ws.range('A3').options(ndim=1).formula = rng_to_paste

基于KrisG的答案,这对我有用:

formula = xw.sheets[0].range("A1").formula
xw.sheets[0].range("A1,A3").formula = formula

结果:

A
1    =C1+$D$1
2
3    =C3+$D$1

基本上,它使用相同的公式覆盖 A1,但这给了它一个参考点,因此它知道如何修改 A3 的公式。

您可以分配范围的公式属性,该属性将使用调整后的公式更新区域中隐式分配的单元格。但是,使用此方法,xlwings 不知道您从哪里复制公式,因此它只能相对于分配的公式递增行/列。

xw.sheets[0].range('A1:A5').value = [[i] for i in range(5)]
xw.sheets[0].range('B1:C5').formula = [['=A1+1','=B1*10']]
xw.sheets[0].range('A1:C5').value
Out[3]: 
[[0.0, 1.0, 10.0],
[1.0, 2.0, 20.0],
[2.0, 3.0, 30.0],
[3.0, 4.0, 40.0],
[4.0, 5.0, 50.0]]

我的解决方法是调用 Excel 宏为我进行复制粘贴。尝试将工作表和范围对象传递到宏时遇到错误,因此下面的代码仅使用字符串标识符。

def copypaste_range(wb_string,
ws_source_string, 
rng_to_copy_string, 
ws_destination_string, 
rng_to_paste_string):
import xlwings as xw
xw.App.display_alerts = False
folder = r'D:My Documents'
xls_path = folder + r'xlwings_macros.xlsb'
wb_macros = xw.Book(xls_path)
wb_macro = wb_macros.macro('copypaste_range')
wb_macro(wb_string,
ws_source_string, 
rng_to_copy_string, 
ws_destination_string, 
rng_to_paste_string)
xw.App.display_alerts = True
wb_macros.close()

VBA

Public Sub copypaste_range(wb_string, _
ws_source_string, rng_to_copy_string, _
ws_destination_string, rng_to_paste_string)
Dim wb As Workbook
Dim fso As New FileSystemObject
If Not IsWorkBookOpen(wb_string) Then
Set wb = Workbooks.Open(fileName:=wb_string)
Else
wb_string = fso.GetFileName(wb_string)
Set wb = Workbooks(wb_string)
End If
Dim rng_to_copy As Range
Dim rng_to_paste As Range
Set rng_to_copy = wb.Sheets(ws_source_string).Range(rng_to_copy_string)
Set rng_to_paste = wb.Sheets(ws_destination_string).Range(rng_to_paste_string)
rng_to_copy.Copy _
Destination:=rng_to_paste
End Sub

最新更新