Jam*_*ton 2 python excel 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
Run Code Online (Sandbox Code Playgroud)
基于 KrisG 的回答,这对我有用:
formula = xw.sheets[0].range("A1").formula
xw.sheets[0].range("A1,A3").formula = formula
Run Code Online (Sandbox Code Playgroud)
结果:
A
1 =C1+$D$1
2
3 =C3+$D$1
Run Code Online (Sandbox Code Playgroud)
基本上,它使用相同的公式覆盖 A1,但这给了它一个参考点,因此它知道如何修改 A3 的公式。
我的解决方法是调用 Excel 宏来为我进行复制粘贴。我在尝试将 Worksheet 和 Range 对象传递给宏时遇到错误,因此下面的代码仅使用字符串标识符。
Python
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()
Run Code Online (Sandbox Code Playgroud)
编程语言
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
Run Code Online (Sandbox Code Playgroud)