Archive

How to use Application.ShowSelectionFloaties in the xlwings API way

The ShowSelectionFloaties property of the Application object in Excel is a useful feature for controlling the visibility of selection floaties—those small, dynamic pop-up toolbars that appear near a selected cell or range in Excel, offering quick access to formatting and data analysis tools like sorting, filtering, and chart recommendations. In xlwings, this property can be accessed and manipulated to enhance user experience by hiding these floaties when they might be distracting, such as during automated report generation or when running macros that require a clean interface.

Syntax and Usage in xlwings

In xlwings, you interact with Excel’s VBA object model through the app object, which represents the Excel application. The ShowSelectionFloaties property is a boolean property, meaning it can be set to either True or False. The syntax for accessing and setting this property is straightforward:

app.api.ShowSelectionFloaties
  • Property Type: Boolean (bool in Python).
  • Get Value: To check the current state, simply read the property: current_state = app.api.ShowSelectionFloaties. This returns True if selection floaties are visible, and False if they are hidden.
  • Set Value: To change the visibility, assign a boolean value: app.api.ShowSelectionFloaties = False to hide floaties, or app.api.ShowSelectionFloaties = True to show them.

There are no parameters for this property, as it is a simple toggle. However, it’s important to note that changes made via xlwings are applied immediately to the Excel instance and affect all open workbooks. This property is part of the Excel Application object, so it controls the global setting for the entire Excel session.

Code Examples

Here are practical examples of using ShowSelectionFloaties in xlwings to manage the visibility of selection floaties:

  1. Hiding Selection Floaties During an Automated Task
    This example demonstrates how to hide floaties before performing a series of operations to prevent them from interfering with the automation, then restore the original setting afterward.
import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active

# Save the current state of ShowSelectionFloaties
original_state = app.api.ShowSelectionFloaties

# Hide the selection floaties
app.api.ShowSelectionFloaties = False

# Perform automated tasks, such as formatting a range
wb = app.books.active
sheet = wb.sheets[0]
sheet.range('A1:D10').value = [[i * j for j in range(1, 5)] for i in range(1, 11)]
sheet.range('A1:D10').api.AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2)

# Restore the original state of ShowSelectionFloaties
app.api.ShowSelectionFloaties = original_state
  1. Toggling Selection Floaties Based on User Input
    In this scenario, the script checks the current visibility and toggles it based on a condition, such as user preference from a simple input.
import xlwings as xw

app = xw.apps.active

# Simulate a user preference (e.g., from a configuration file or input)
user_wants_floaties = False # Assume user prefers hidden floaties

if user_wants_floaties:
    app.api.ShowSelectionFloaties = True
    print("Selection floaties are now visible.")
else:
    app.api.ShowSelectionFloaties = False
    print("Selection floaties are now hidden.")
  1. Ensuring a Clean Interface for a Dashboard
    When generating a dashboard, you might want to hide floaties to maintain a professional appearance, especially before saving or exporting the workbook.
import xlwings as xw

app = xw.apps.active
wb = app.books.active

# Hide floaties before finalizing the dashboard
app.api.ShowSelectionFloaties = False

# Perform dashboard updates (e.g., refresh charts, pivot tables)
# ... (your dashboard code here)

# Save the workbook with floaties hidden
wb.save(r'C:\Path\To\Dashboard.xlsx')

# Optionally, re-enable floaties if needed for further interaction
# app.api.ShowSelectionFloaties = True

How to use Application.ShowQuickAnalysis in the xlwings API way

The ShowQuickAnalysis property of the Application object in Excel, accessible via the xlwings library in Python, provides a convenient way to programmatically trigger the Quick Analysis feature. This feature, when invoked, offers users a context-sensitive menu with various tools for data analysis and visualization, such as conditional formatting, charts, totals, tables, and sparklines. It is particularly useful for enhancing data presentation and gaining insights directly from a selected range without navigating through multiple ribbon tabs. In xlwings, this functionality is exposed as a property of the application instance, allowing for seamless integration into automated Excel workflows.

The syntax for accessing this property in xlwings is straightforward. It is called on the application object, which represents the Excel instance. Since ShowQuickAnalysis is a property, it can be set to True or False to control the visibility of the Quick Analysis tooltip. Typically, it is set to True to display the tooltip for a specific range. The property does not take any arguments directly, but its effect is applied to the currently selected range in the active workbook. To use it effectively, you should first select the desired range of cells before setting the property.

Here is a basic code example demonstrating its usage:

import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active

# Open a workbook or use the active one
wb = app.books.active

# Select a specific range, e.g., A1:D10, which contains data for analysis
ws = wb.sheets.active
ws.range('A1:D10').select()

# Show the Quick Analysis tooltip for the selected range
app.ShowQuickAnalysis = True

How to use Application.ShowMenuFloaties in the xlwings API way

The ShowMenuFloaties member of the Application object in Excel controls whether context-sensitive tooltips (also known as “ScreenTips” or “floaties”) are displayed for menus and commands in the Excel user interface. This property is part of the Excel object model and can be accessed via the xlwings library in Python to programmatically manage the visibility of these UI hints, which can enhance user experience or reduce on-screen clutter during automated processes.

Functionality:
ShowMenuFloaties is a Boolean property that determines if Excel shows descriptive tooltips when the user hovers over menu items, ribbon buttons, or other command elements. When set to True, these floaties are visible; when False, they are hidden. This can be useful in automation scripts where you want to standardize the UI state or minimize distractions during macro execution.

Syntax in xlwings:
In xlwings, you access this property through the app object, which represents the Excel Application. The syntax is straightforward as it involves getting or setting a property value. There are no parameters for this property, as it is a simple Boolean toggle.

  • To get the current state:
current_state = app.api.ShowMenuFloaties

This returns True if menu floaties are shown, False otherwise.

  • To set the state:
app.api.ShowMenuFloaties = False # Hides menu floaties

or

app.api.ShowMenuFloaties = True # Shows menu floaties

Code Examples:
Here are practical xlwings API examples demonstrating how to use ShowMenuFloaties:

  1. Hiding Menu Floaties During an Automation Task:
    This example temporarily disables menu floaties to clean up the UI while performing data operations, then restores the original setting.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Store the original state
original_state = app.api.ShowMenuFloaties

# Hide menu floaties
app.api.ShowMenuFloaties = False

# Perform some Excel tasks (e.g., data processing)
wb = app.books.active
sheet = wb.sheets[0]
sheet.range('A1').value = 'Processing data...'
# ... additional automation code ...

# Restore the original state
app.api.ShowMenuFloaties = original_state
  1. Checking and Toggling the Menu Floaties Setting:
    This example checks the current visibility and toggles it based on a condition.
import xlwings as xw

app = xw.apps.active

# Check if menu floaties are currently shown
if app.api.ShowMenuFloaties:
    print("Menu floaties are visible. Hiding them now.")
    app.api.ShowMenuFloaties = False
else:
    print("Menu floaties are hidden. Showing them now.")
    app.api.ShowMenuFloaties = True
  1. Ensuring a Clean UI for a Report Generation Macro:
    In this scenario, menu floaties are turned off during report generation to prevent visual interference, and the setting is reverted afterward.
import xlwings as xw

def generate_report():
app = xw.apps.active
# Disable menu floaties
app.api.ShowMenuFloaties = False

# Generate report logic
wb = app.books.active
# ... code to format and populate the report ...

# Re-enable menu floaties
app.api.ShowMenuFloaties = True
print("Report generated with menu floaties managed.")

# Run the function
generate_report()

How to use Application.ShowDevTools in the xlwings API way

The ShowDevTools member of the Application object in Excel’s object model provides control over the visibility of the VBA (Visual Basic for Applications) development environment, commonly known as the VBA Editor or IDE (Integrated Development Environment). When automating Excel with xlwings, this property allows you to programmatically show or hide the VBA Editor window, which is useful during development, debugging, or when creating macros and user forms. It’s a Boolean property that can be set to True to display the editor or False to hide it, and it can also be read to check the current visibility state.

In xlwings, you access this property through the api property of the App or Book objects, which exposes the underlying Excel VBA object model. The syntax for using ShowDevTools is straightforward, as it maps directly to the Excel object model.

Syntax in xlwings:

  • To get the current visibility state: app.api.ShowDevTools
  • To set the visibility state: app.api.ShowDevTools = True or app.api.ShowDevTools = False

Where app is an instance of xw.App representing the Excel application. The property accepts and returns a Boolean value:

  • True: Makes the VBA Editor visible.
  • False: Hides the VBA Editor.

Note: This property is specific to the Excel application instance and affects the VBA Editor globally for that instance. It may not be available or have an effect if VBA is disabled or not installed (e.g., in some Excel runtime environments). Always ensure the Excel instance has VBA support.

Code Examples with xlwings:

  1. Showing the VBA Editor:
    This example starts an Excel application, makes it visible, and then opens the VBA Editor.
import xlwings as xw
# Start a new Excel application
app = xw.App(visible=True)
# Show the VBA Developer Tools (Editor)
app.api.ShowDevTools = True
# Keep the application open for demonstration
input("Press Enter to close Excel...")
app.quit()
  1. Toggling VBA Editor Visibility:
    This example checks the current state of the VBA Editor, toggles it, and prints a message.
import xlwings as xw
app = xw.App(visible=True)
# Get current visibility state
current_state = app.api.ShowDevTools
print(f"VBA Editor is currently visible: {current_state}")
# Toggle the state
app.api.ShowDevTools = not current_state
print(f"Toggled visibility. Now visible: {app.api.ShowDevTools}")
# Clean up
app.quit()
  1. Conditional Display Based on Debug Mode:
    In a script, you might want to show the VBA Editor only during debugging or development phases.
import xlwings as xw
DEBUG_MODE = True # Set to False in production
app = xw.App(visible=True)
if DEBUG_MODE:
    app.api.ShowDevTools = True
    print("Debug mode: VBA Editor shown.")
else:
    app.api.ShowDevTools = False
    print("Production mode: VBA Editor hidden.")
# Perform other automation tasks...
app.quit()

How to use Application.ShowChartTipValues in the xlwings API way

In the Excel object model, the Application.ShowChartTipValues property is a member of the top-level Application object. This property controls whether chart tip values (also known as data labels or tooltips) are displayed when you hover the mouse pointer over a data point in a chart within Excel. When enabled, users can see the exact numeric value of a data point directly on the chart, enhancing data visualization and analysis. This setting applies globally to all open workbooks in the Excel instance.

In xlwings, you can access and manipulate this property through the api property of the App object, which provides a direct gateway to the underlying Excel Application object via the COM interface. The xlwings API call follows the pattern: app.api.ShowChartTipValues, where app is an instance of xlwings.App. This property is a Boolean value, meaning it can be set to True to enable chart tip values or False to disable them. You can also retrieve its current state to check if the feature is active.

The syntax for using ShowChartTipValues in xlwings is straightforward:

  • To get the current setting: current_setting = app.api.ShowChartTipValues
  • To set the setting: app.api.ShowChartTipValues = True or app.api.ShowChartTipValues = False

There are no parameters for this property, as it is a simple Boolean attribute. However, it’s important to note that changes made to this property affect the entire Excel application session. This means that all charts across all open workbooks will adhere to this setting until it is changed again or Excel is closed. It’s a useful feature for presentations or reports where you might want to temporarily hide or show data values for clarity.

Here is a practical xlwings API code example that demonstrates how to use the ShowChartTipValues property:

import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active if xw.apps.active else xw.App()

# Get the current state of ShowChartTipValues
current_state = app.api.ShowChartTipValues
print(f"Current ShowChartTipValues setting: {current_state}")

# Disable chart tip values
app.api.ShowChartTipValues = False
print("Chart tip values have been disabled.")

# Perform some chart-related operations, e.g., open a workbook with a chart
wb = app.books.open('example.xlsx')
chart = wb.sheets[0].charts[0] # Assuming the first chart on the first sheet
# At this point, hovering over chart data points will not show values

# Re-enable chart tip values
app.api.ShowChartTipValues = True
print("Chart tip values have been re-enabled.")

# Close the workbook without saving
wb.close()

# Optionally, reset to the original state if needed
app.api.ShowChartTipValues = current_state

# Quit the Excel application if it was started by this script
if not xw.apps.active:
app.quit()

How to use Application.ShowChartTipNames in the xlwings API way

The ShowChartTipNames property of the Application object in Excel is a setting that controls whether chart tip names are displayed. Chart tips are the small pop-up labels that appear when you hover the mouse pointer over a chart element, such as a data point, series, or axis title. These tips typically show the name and value of the element. When ShowChartTipNames is set to True, these names are included in the tooltip. When set to False, only the values are shown, if applicable. This property is part of a group of settings that manage on-screen feedback and can be useful for creating cleaner visual presentations or for users who are already familiar with the chart’s data structure and do not require the additional descriptive text.

In the xlwings library, which provides a Pythonic interface to automate and interact with Excel, you access this property through the Application object. The syntax is straightforward, as it is a simple property getter and setter. The property expects a Boolean value (True or False).

xlwings API Syntax:

app = xw.App() # Get the active or a new Excel application instance
# To get the current setting
current_setting = app.api.ShowChartTipNames
# To set the property
app.api.ShowChartTipNames = True # or False

Here, app.api provides direct access to the underlying Excel VBA object model. The ShowChartTipNames property does not take any arguments; it is simply read or written to.

Code Example:
The following example demonstrates how to toggle the ShowChartTipNames setting and verify its state. This can be integrated into a larger script that prepares an Excel environment for a specific reporting task, ensuring that chart tooltips conform to a desired standard.

import xlwings as xw

# Connect to the active Excel instance
with xw.App(visible=True) as app:
# Get the current setting and print it
original_setting = app.api.ShowChartTipNames
print(f"Original ShowChartTipNames setting: {original_setting}")

# Disable the display of names in chart tips
app.api.ShowChartTipNames = False
print("ShowChartTipNames has been set to False. Chart tooltips will now only show values.")

# For demonstration, create a simple chart to see the effect
wb = app.books.add()
sheet = wb.sheets[0]
# Add some sample data
sheet.range('A1').value = [['Category', 'Value'],
['A', 10],
['B', 20],
['C', 15]]
# Create a chart
chart = sheet.charts.add()
chart.set_source_data(sheet.range('A1').expand())
chart.chart_type = 'column_clustered'
chart.api[1].HasTitle = True
chart.api[1].ChartTitle.Text = "Sample Chart"

# Pause to allow user to hover over chart and observe tooltips
input("Hover over a column in the chart. The tooltip should show only the value (e.g., '20'). Press Enter to continue...")

# Re-enable the display of names
app.api.ShowChartTipNames = True
print("ShowChartTipNames has been restored to True. Tooltips will now show names and values.")

input("Hover over a column again. The tooltip should now show both name and value (e.g., 'B: 20'). Press Enter to exit...")

# Optionally, restore the original setting before closing
app.api.ShowChartTipNames = original_setting
wb.close()

How to use Application.SheetsInNewWorkbook in the xlwings API way

The SheetsInNewWorkbook property of the Application object in Excel specifies the number of worksheets that are automatically included when a new workbook is created. This setting is a global option within the Excel application instance, allowing users or automation scripts to define a default sheet count, which can improve efficiency by avoiding the need to manually add sheets after workbook creation. In xlwings, this property is accessed through the Application object, providing a programmatic way to both retrieve and modify this default value.

Functionality:
The primary function is to control the default number of worksheets in new workbooks. This is particularly useful in automation scenarios where a consistent starting structure is required, or when preparing templates that need multiple sheets by default.

Syntax:

# To get the current setting
current_sheet_count = xw.apps[0].api.SheetsInNewWorkbook

# To set a new value
xw.apps[0].api.SheetsInNewWorkbook = new_count
  • xw.apps[0]: Represents the first (or a specific) Excel application instance controlled by xlwings. Use xw.apps.active for the active instance if multiple are open.
  • .api: Provides direct access to the underlying Excel object model (the COM API).
  • SheetsInNewWorkbook: The property being accessed. It expects an integer value.

Parameter/Value Details:

  • Type: Read/Write Property (Integer).
  • Value Range: The number must be an integer between 1 and 255, inclusive. Excel enforces these limits.
  • Default: Typically 1 in a standard Excel installation.
  • Persistence: This is an application-level setting in the current session. It is not permanently saved between Excel sessions unless configured within Excel’s options or set via a macro that runs on startup.

Code Examples:

  1. Retrieving the Current Default:
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Get the current default number of sheets
default_sheets = app.api.SheetsInNewWorkbook
print(f"New workbooks currently start with {default_sheets} sheet(s).")
# Output example: New workbooks currently start with 1 sheet(s).
  1. Changing the Default and Creating a Workbook:
import xlwings as xw

app = xw.apps.active

# Set the default to 3 worksheets
app.api.SheetsInNewWorkbook = 3

# Create a new workbook. It will now contain 3 worksheets automatically.
new_wb = app.books.add()
print(f"New workbook has {len(new_wb.sheets)} sheets.")
# Output: New workbook has 3 sheets.

# List the sheet names
for sheet in new_wb.sheets:
print(sheet.name)
# Output: Sheet1, Sheet2, Sheet3
  1. Resetting to the Standard Default:
import xlwings as xw

app = xw.apps.active
# Reset to the common default of 1 sheet
app.api.SheetsInNewWorkbook = 1

How to use Application.Sheets in the xlwings API way

The Application.Sheets property in Excel’s object model provides a collection of all sheets within the open workbook, encompassing both worksheets and chart sheets. In xlwings, this is accessed via the app object, which represents the Excel application instance. The primary function is to retrieve a list or a specific sheet, enabling operations across multiple sheets or referencing sheets by name or index. This is essential for automating tasks that involve iterating through all sheets, checking their properties, or performing bulk operations.

Syntax in xlwings:
The property is accessed as app.sheets. It returns a Sheets collection object. To reference a specific sheet, you can use indexing or a sheet name.

  • app.sheets: Returns the collection of all sheets.
  • app.sheets[index]: Returns the sheet at the specified index (1-based).
  • app.sheets[name]: Returns the sheet with the given name.

Parameters:

  • index: An integer representing the sheet’s position in the workbook (starting from 1). For example, app.sheets[1] refers to the first sheet.
  • name: A string representing the exact name of the sheet, such as app.sheets["Sheet1"].

Code Examples:

  1. Iterate through all sheets and print names:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
for sheet in app.sheets:
    print(sheet.name)
wb.close()
app.quit()
  1. Access a specific sheet by name and modify a cell:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
target_sheet = app.sheets["DataSheet"]
target_sheet.range("A1").value = "Updated Value"
wb.save()
wb.close()
app.quit()
  1. Count the number of sheets and check types:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
sheet_count = len(app.sheets)
print(f"Total sheets: {sheet_count}")
# To check if a sheet is a worksheet (vs. chart sheet), use its type property
for sheet in app.sheets:
if sheet.type == 'chart':
    print(f"{sheet.name} is a chart sheet.")
else:
    print(f"{sheet.name} is a worksheet.")
wb.close()
app.quit()
  1. Add a new sheet and rename it using the collection:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
new_sheet = wb.sheets.add()
new_sheet.name = "Analysis"
# Access via app.sheets to confirm
print("Sheet names:", [s.name for s in app.sheets])
wb.save()
wb.close()
app.quit()

How to use Application.SensitivityLabelPolicy in the xlwings API way

The SensitivityLabelPolicy member of the Application object in Excel refers to a feature related to Microsoft Information Protection (MIP) sensitivity labels. These labels are used to classify and protect sensitive data within Office documents by applying encryption, watermarks, or access restrictions based on organizational policies. In xlwings, you can interact with this functionality to retrieve or set sensitivity label information for an Excel workbook programmatically, enabling automation of compliance and security tasks directly from Python.

Functionality
The SensitivityLabelPolicy provides access to the sensitivity label assigned to the active workbook. It allows you to get the current label’s details, such as its name, ID, and protection settings, or to apply a new label. This is particularly useful in enterprise environments where documents must adhere to data governance standards. Through xlwings, you can integrate these capabilities into larger data processing workflows, ensuring that workbooks are automatically classified according to predefined policies without manual intervention.

Syntax
In xlwings, you access the SensitivityLabelPolicy via the Application object. The typical syntax is:

import xlwings as xw
app = xw.App(visible=False) # Or use xw.apps.active for an existing instance
sensitivity_label = app.api.ActiveWorkbook.SensitivityLabel.Policy

Here, app.api provides the underlying COM object for Excel’s Application, allowing direct access to the VBA object model. The SensitivityLabel.Policy returns an object representing the current sensitivity label policy. To get specific properties, you can use methods like GetLabel or SetLabel, but note that the exact properties and methods depend on Excel’s object model and may require exploration via dir() or Excel’s VBA documentation. Common properties include:

  • Name: The display name of the sensitivity label.
  • Id: A unique identifier for the label.
  • IsEnabled: Indicates if the label is active (Boolean).
    Parameters for methods like SetLabel typically include the label ID or name, and sometimes additional settings like protection options. Refer to Microsoft’s official documentation for detailed parameter lists, as they can vary with Excel versions.

Example
Below is a practical xlwings code example that retrieves and sets a sensitivity label. This assumes you have an Excel workbook open with sensitivity labels configured in your organization.

import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active
wb = app.books.active

# Access the SensitivityLabelPolicy
policy = wb.api.SensitivityLabel.Policy

# Get current label information
try:
    label_info = policy.GetLabel()
    print(f"Current Sensitivity Label: {label_info.Name}")
    print(f"Label ID: {label_info.Id}")
except Exception as e:
    print(f"No label applied or error: {e}")

# Set a new sensitivity label (replace 'Your-Label-ID' with an actual ID)
# Note: Setting labels may require specific permissions and label IDs from your organization.
new_label_id = "Your-Label-ID" # Example ID; obtain from your MIP configuration
try:
    policy.SetLabel(new_label_id, "Set by xlwings")
    print("Sensitivity label updated successfully.")
except Exception as e:
    print(f"Failed to set label: {e}")

# Save and close
wb.save()
app.quit()

How to use Application.Selection in the xlwings API way

The Application.Selection member in the Excel object model is a powerful property that returns the currently selected object in the active window of the Excel application. This could be a Range, a Chart, a Shape, or any other selectable object. In xlwings, this property is accessed via the api property, which provides direct access to the underlying COM object model. It is particularly useful for writing macros or scripts that interact dynamically with the user’s current selection, enabling context-sensitive operations without hardcoding specific cell references or object names.

Functionality:
The primary function is to retrieve the object that is currently selected by the user in the Excel interface. This allows your xlwings script to perform operations on whatever the user has highlighted, such as reading data from a selected range, formatting it, or manipulating a selected chart. It enhances interactivity and flexibility in automation scripts.

Syntax:
In xlwings, you access this property through the Application object. The general syntax is:

selected_object = xw.apps[0].api.Selection
  • xw.apps[0]: This refers to the first (or typically the active) Excel application instance. You can use xw.apps.active if you have a specific instance active.
  • .api: This is the gateway to the native Excel object model (via COM).
  • .Selection: This property returns a COM object representing the current selection. Its type varies based on what is selected.

To work with the returned object effectively, you often need to check its type or convert it to an xlwings object. For example, if a Range is selected, you can wrap it with xw.Range for easier manipulation within xlwings.

Examples:
Here are several xlwings API code instances demonstrating the use of Application.Selection:

  1. Getting the Address of a Selected Range:
    This example retrieves the address of the currently selected cells and prints it.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active
# Get the current selection
selection = app.api.Selection
# Check if it's a Range (to avoid errors)
if selection.Type == 8: # 8 corresponds to xlRange in Excel constants
    range_address = selection.Address
    print(f"Selected range address: {range_address}")
  1. Reading Values from a Selected Range:
    This reads the values from the selected range and converts them into a list of lists using xlwings.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
if hasattr(selection, 'Value'): # Check if it has a Value property (like Range)
    # Wrap the COM Range with xlwings Range for .value property
    xl_range = xw.Range(selection)
    data = xl_range.value
    print(f"Selected data: {data}")
  1. Formatting the Selected Range:
    This changes the interior color of the selected cells to yellow.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
if selection.Type == 8:
    selection.Interior.Color = 65535 # Yellow color in RGB
  1. Working with a Selected Chart:
    If a chart is selected, this example changes its title.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
# Check if it's a Chart (Type 3 for xlChart)
if selection.Type == 3:
    selection.ChartTitle.Text = "Updated Chart Title via xlwings"
  1. Handling Multiple Selection Types:
    A more robust example that handles different selection types gracefully.
import xlwings as xw

app = xw.apps.active
selection = app.api.Selection
selection_type = selection.Type

if selection_type == 8: # Range
    print(f"Range selected: {selection.Address}")
elif selection_type == 3: # Chart
    print("A chart is selected.")
elif selection_type == 4: # Shape
    print("A shape is selected.")
else:
    print(f"Other selection type: {selection_type}")