The FillRight method of the Range object in xlwings is a powerful tool for replicating data or formulas across a horizontal range in an Excel worksheet. It is particularly useful for quickly populating adjacent cells with the content of the leftmost cell in a selection, effectively performing a “fill right” operation similar to dragging the fill handle in Excel. This method is efficient for applying consistent calculations, labels, or formats across rows without manual repetition.
Syntax:
Range.FillRight()
This method does not require any parameters. It operates on a Range object, which specifies the target cells. The leftmost cell of the range provides the source content (value, formula, or format), and the method fills this content into all other cells to the right within the specified range. The range must include at least two columns for the fill to have an effect; if the range is only one column wide, FillRight will have no visible impact.
Key Points:
- The
FillRightmethod copies both values/formulas and formatting from the leftmost cell to the other cells in the range. - It is equivalent to the Excel action of selecting a range and using “Fill Right” from the Home tab or dragging the fill handle to the right.
- This method is part of xlwings’ API that mirrors Excel’s VBA object model, providing a programmatic way to automate tasks in Python.
Examples:
- Basic Fill Right with Values:
Suppose you have a value in cell A1 and want to fill it across to D1.
import xlwings as xw
wb = xw.Book("example.xlsx")
sheet = wb.sheets["Sheet1"]
sheet.range("A1:D1").FillRight()
After execution, if A1 contains “Start”, cells B1, C1, and D1 will also contain “Start”.
- Fill Right with Formulas:
If cell A2 has a formula like=SUM(B2:E2), filling it right can apply similar calculations across columns.
sheet.range("A2:C2").FillRight()
This will copy the formula to B2 and C2, adjusting references relatively (e.g., B2 will have =SUM(C2:F2) if relative referencing is used).
- Combined with Other Operations:
You can useFillRightafter setting an initial value or formula programmatically.
sheet.range("A3").value = "Header"
sheet.range("A3:D3").FillRight() # Fills "Header" across B3, C3, D3
- Filling Across Multiple Rows:
The range can span multiple rows, filling each row independently from its leftmost cell.
sheet.range("A4:D6").FillRight()
Leave a Reply