簡體   English   中英

具有相對單元格引用的Python xlwings復制粘貼公式

[英]Python xlwings copy-paste formula with relative cell references

我在單元格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

我的解決方法是調用Excel宏來為我執行復制粘貼。 我在嘗試將Worksheet和Range對象傳遞給宏時遇到錯誤,因此下面的代碼只使用了字符串標識符。

蟒蛇

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

您可以指定范圍的公式屬性,該范圍將使用調整后的公式更新范圍中隱式指定的單元格。 但是,使用此方法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]]

基於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的公式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM