怎样用excel写脚本
1. 怎样在excel中使用python脚本
打开excel的vba编辑器,敲入以下代码即可:
打开:文件-》导入,加载xlwings.bas进去
编辑function setting文件:
PYTHON_WIN = ""
PYTHON_MAC = ""
PYTHON_FROZEN = ThisWorkbook.Path & "\build\exe.win32-2.7"
PYTHONPATH = ThisWorkbook.Path
UDF_MODULES = ""
UDF_DEBUG_SERVER = False
LOG_FILE = ""
SHOW_LOG = True
OPTIMIZED_CONNECTION = False
编写sub模块运行:
Sub HelloWorld()
RunPython ("import hello; hello.world()")
End Sub
实际调用的方法:
# hello.py
import numpy as np
import xlwings as xw
def world():
wb = xw.Book.caller()
wb.sheets[0].range('A1').value = 'Hello World!'
2. 怎样在Excel中使用python脚本
在Excel中准备调用的python代码:
def merge_sort_unique(lists):
s = set()
for L in lists:
s.update(L)
return sorted(s)
任意在本地建立一个目录,并保存这个代码并命名为Methods.py。我们一步步看看如何从Excel的工作表中如何调用这个脚本。打开Excel,填写一些数据以便提供python脚本处理,并保持这个表格于刚才的python脚本在同一目录下。你的工作表应该如下:
现在,备调用python脚本,创建一个新的模块(Insert | Mole)并敲以下VBA代码:
Function msu(lists As Range)
Set methods = PyMole("Methods", AddPath:=ThisWorkbook.Path)
Set result = PyCall(methods, "merge_sort_unique", PyTuple(lists.Value2))
msu = WorksheetFunction.Transpose(PyVar(result))
ExitFunction
EndFunction