Python

Python 呼叫 Excel VBA 自動化執行巨集程式教學與範例

使用 Python 的 pywin32 模組,串接 Excel VBA 巨集程式,自動化執行大量程式。

Python 是一種很適合用來串接各種組件,進行系統整合的程式語言,如果我們有許多 Excel 的 VBA 巨集程式,想要讓它們可以自動化執行,就可以考慮使用 Python 來處理。

Python pywin32 模組

Python 的 pywin32 模組提供了許多 Windows API 擴充功能,如果想要在 Python 中操作 Excel 或呼叫 VBA,就可以使用這個套件。

請先按照 pywin32 安裝與使用教學,將 pywin32 模組安裝好。

Excel VBA 巨集程式

準備一些簡單的 Excel VBA 巨集程式,這裡我們開啟 Excel 的 VBA 巨集程式編輯器,撰寫一個子程序(Sub)與一個函數(Function):

Sub hello()
  MsgBox "Hello, World."
End Sub

Function hello2(name As String)
  hello2 = "Hello, " & name & "!"
End Function

編輯完成後,記得將檔案儲存為「Excel 啟用巨集的活頁簿(*.xlsm)」。

Excel VBA 巨集程式

Python 呼叫 Excel VBA 巨集程式

以下是一個在 Python 中開啟 Excel,執行 VBA 巨集程式的範例指令稿,對於普通的子程序(Sub)就直接以 Application.Run 執行即可,而若是有傳回值的函數(Function),也可以直接取得計算完的結果:

import os
import win32com.client

# 開啟 Excel
excel = win32com.client.Dispatch("Excel.Application")

# 開啟 hello.xlsm 活頁簿檔案
excel.Workbooks.Open(Filename="C:OfficeGuidehello.xlsm")

# 執行巨集程式
excel.Application.Run("hello.xlsm!hello")

# 傳入參數,並取得計算結果
result = excel.Application.Run("hello.xlsm!hello2", "OfficeGuide.cc")
print(result)

# 離開 Excel
excel.Application.Quit()

# 清理 com 介面
del excel

執行之後,就會看到由 Excel VBA 所顯示的訊息視窗:

Excel VBA 訊息視窗

關閉第一個訊息視窗之後,接著即可看到由 Excel VBA 傳回 Python 的計算結果:

Excel VBA 傳回計算結果

透過這樣簡單的串接方式,我們就可以使用 Python 輕易地整合大量的 Excel VBA 程式,讓執行流程自動化。

參考資料:Stack OverflowExcel 物件模型總覽

Share
Published by
Office Guide
Tags: VBA

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago