天天看点

配置Office Excel运行Python宏脚本

配置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就停止服务了...)

配置Office Excel运行Python宏脚本

2.安装Python

安装前,勾选

Add Python 3.x to PATH

选项。安装完毕之后,在Windows控制台可直接使用

python

命令。

配置Office Excel运行Python宏脚本

3.检查是否安装成功

Win+R

,打开

运行

,输入

PowerShell

,打开命令行。

输入

python -V

,查看Python版本号。

配置Office Excel运行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

或点击此处直接下载

配置Office Excel运行Python宏脚本
配置Office Excel运行Python宏脚本
配置Office Excel运行Python宏脚本
配置Office Excel运行Python宏脚本
配置Office Excel运行Python宏脚本

2.新建一个Excel文件,打开可在标签栏显示

ExcelPython

标签

配置Office Excel运行Python宏脚本

3.打开Excel选项——信任中心——信任中心设置——宏设置——安全性,选中“信任对于VBA工程对象模型的访问”,按确定即可。

配置Office Excel运行Python宏脚本

测试安装是否正确

1.将创建的

data.xlsx

文件另存为

data.xlsm

宏文件。

2.回到Excel,点击

ExcelPython

标签的

Setup ExcelPython

按钮

配置Office Excel运行Python宏脚本

3.桌面上会出现一个名为

xlpython

的文件夹,以及一个与

*.xlsm

文件同名的

*.py

文件。

配置Office Excel运行Python宏脚本

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

           
配置Office Excel运行Python宏脚本

5.回到Excel中,点击

ExcelPython

标签的

Import Python UDFs

按钮

配置Office Excel运行Python宏脚本

6.使用Python中定义的函数

在输入框中输入

=getRandomBirth()

配置Office Excel运行Python宏脚本

效果如图

配置Office Excel运行Python宏脚本

7.在Excel中使用定义的第二个函数

配置Office Excel运行Python宏脚本

效果如图

配置Office Excel运行Python宏脚本

至此,可以使用Python进行Excel宏的开发

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