配置Office Excel運行Python宏腳本


基本環境

名稱 版本
操作系統 Windows 10 x64
Office 2016

安裝Python

1.下載Python安裝包

登錄https://www.python.org/downloads/windows/進行下載
Python2.x或Python3.x均可,推薦Python3.x(因為2020年1月1日起Python2就停止服務了...)

2.安裝Python

安裝前,勾選Add Python 3.x to PATH選項。安裝完畢之后,在Windows控制台可直接使用python命令。

3.檢查是否安裝成功

Win+R,打開運行,輸入PowerShell,打開命令行。
輸入python -V,查看Python版本號。

4.安裝PythonWin32庫

Python2.x 按以下方式安裝

pip install pypiwin32 -i https://mirrors.aliyun.com/pypi/simple/

Python3.x 按以下方式安裝

pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple/

安裝ExcelPython

1.從https://sourceforge.net/projects/excelpython/files/處,下載ExcelPython

點擊此處直接下載

2.新建一個Excel文件,打開可在標簽欄顯示ExcelPython標簽

3.打開Excel選項——信任中心——信任中心設置——宏設置——安全性,選中“信任對於VBA工程對象模型的訪問”,按確定即可。

測試安裝是否正確

1.將創建的data.xlsx文件另存為data.xlsm宏文件。

2.回到Excel,點擊ExcelPython標簽的Setup ExcelPython按鈕

3.桌面上會出現一個名為xlpython的文件夾,以及一個與*.xlsm文件同名的*.py文件。

4.打開data.py編輯,寫入以下內容

from xlpython import *
import random

@xlfunc
def getRandomBirth():
    y = random.randint(1980, 2000)
    m = random.randint(1, 12)
    d = random.randint(1, 28)
    return str(y)+'/'+str(m)+'/'+str(d)

@xlfunc
def getAge(d):
    _today = [ 2019, 8, 30 ]
    _list = str(d).split('/')
    age = _today[0] - int(_list[0])
    if _today[1] < int(_list[1]):
        age -= 1
    elif _today[1] == int(_list[1]):
        if _today[2] < int(_list[2]):
            age -= 1
        else:
            pass
    else:
        pass
    return age

5.回到Excel中,點擊ExcelPython標簽的Import Python UDFs按鈕

6.使用Python中定義的函數
在輸入框中輸入=getRandomBirth()

效果如圖

7.在Excel中使用定義的第二個函數

效果如圖

至此,可以使用Python進行Excel宏的開發

本文鏈接: https://www.cnblogs.com/connect/p/office-excel-python-conf.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM