用python批量执行VBA代码

先说下背景环境

  1. 公司需要问卷调查,有两份问卷, 1)是spss问卷,2)是excel问卷。spss问卷数据不全,但有各种标签, excel呢, 生成的数据直接把选项变成了值

  2. 现在需要把excel的选项值变成1, 2这种数字{1:“满意”}

  3. 妹子已经把vba写好了,虽然一堆错误,我百度了半天,改了很多:(

由于需要执行很多vba命令,我就用py的字符串拼接,生成了,900多份,怀疑vba的代码有问题,凭直觉,但我不会vba,又懒得查,只能让cpu去做重复工作了

需要模块win32com

安装方法

```

python3 -m pip install pypiwin32

```

生成vba命令

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import savReaderWriter

filepath = "/opt/code/my_code/testStata/5976d077606f07d4418b46eb160938.sav"

a = ‘‘‘Dim m
m = 1
Columns("‘‘‘

b = ‘‘‘").Select
m = 1
On Error GoTo Err_Handle‘‘‘

c = ‘‘‘

For m = 1 To 65
Selection.Find(What:="‘‘‘

d = ‘‘‘", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, MatchByte:=False, SearchFormat:=False).Activate
ActiveCell.Replace What:="‘‘‘

e = ‘‘‘", Replacement:="‘‘‘

f = ‘‘‘", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next m
‘‘‘

g = ‘‘‘
Exit Sub
Err_Handle:
End Sub

‘‘‘

sum = 0

totalStr = ‘\n************hello************\n\n‘

excelList = [‘A‘,
             ‘B‘,
             ‘C‘,
             ‘D‘,
             ‘E‘,
             ‘F‘,
             ‘G‘,
             ‘H‘,
             ‘I‘,
             ‘J‘,
             ‘K‘,
             ‘L‘,
             ‘M‘,
             ‘N‘,
             ‘O‘,
             ‘P‘,
             ‘Q‘,
             ‘R‘,
             ‘S‘,
             ‘T‘,
             ‘U‘,
             ‘V‘,
             ‘W‘,
             ‘X‘,
             ‘Y‘,
             ‘Z‘,
             "AA",
             "AB",
             "AC",
             "AD",
             "AE",
             "AF",
             "AG",
             "AH",
             "AI",
             "AJ",
             "AK",
             "AL",
             "AM",
             "AN",
             "AO",
             "AP",
             "AQ",
             "AR",
             "AS",
             "AT",
             "AU",
             "AV",
             "AW",
             "AX",
             "AY",
             "AZ",
             "BA",
             "BB",
             "BC",
             "BD",
             "BE",
             "BF",
             "BG",
             "BH",
             "BI",
             "BJ",
             "BK",
             "BL",
             "BM",
             "BN",
             "BO",
             "BP",
             "BQ",
             "BR",
             "BS",
             "BT",
             "BU",
             "BV",
             "BW",
             "BX",
             "BY",
             "BZ",
             "CA",
             "CB",
             "CC",
             "CD",
             "CE",
             "CF",
             "CG",
             "CH",
             "CI",
             "CJ",
             "CK",
             "CL",
             "CM",
             "CN",
             "CO",
             "CP",
             "CQ",
             "CR",
             "CS",
             "CT",
             "CU",
             "CV",
             "CW",
             "CX",
             "CY",
             "CZ",
             "DA",
             "DB",
             "DC",
             "DD",
             "DE",
             "DF",
             "DG",
             "DH",
             "DI",
             "DJ",
             "DK",
             "DL",
             "DM",
             "DN",
             "DO",
             "DP",
             "DQ",
             "DR",
             "DS",
             "DT",
             "DU",
             "DV",
             "DW",
             "DX",
             "DY",
             "DZ",
             "EA",
             "EB",
             "EC",
             "ED",
             "EE",
             "EF",
             "EG",
             "EH",
             "EI",
             "EJ",
             "EK",
             "EL",
             "EM",
             "EN",
             "EO",
             "EP",
             "EQ",
             "ER",
             "ES",
             "ET",
             "EU",
             "EV",
             "EW",
             "EX",
             "EY",
             "EZ",
             "FA",
             "FB",
             "FC",
             "FD",
             "FE",
             "FF",
             "FG",
             "FH",
             "FI",
             "FJ",
             "FK",
             "FL",
             "FM",
             "FN",
             "FO",
             "FP",
             "FQ",
             "FR",
             "FS",
             "FT",
             "FU",
             "FV",
             "FW",
             "FX",
             "FY",
             "FZ",
             "GA",
             "GB",
             "GC",
             "GD",
             "GE",
             "GF",
             "GG",
             "GH",
             "GI",
             "GJ",
             "GK",
             "GL",
             "GM",
             "GN",
             "GO",
             "GP",
             "GQ",
             "GR",
             "GS",
             "GT",
             "GU",
             "GV",
             "GW",
             "GX",
             "GY",
             "GZ",
             "HA",
             "HB",
             "HC",
             "HD",
             "HE",
             "HF",
             "HG",
             "HH",
             "HI",
             "HJ",
             "HK",
             "HL",
             "HM",
             "HN",
             "HO",
             "HP",
             "HQ",
             "HR",
             "HS",
             "HT",
             "HU",
             "HV",
             "HW",
             "HX",
             "HY",
             "HZ",
             "IA",
             "IB",
             "IC",
             "ID",
             "IE",
             "IF",
             "IG",
             "IH",
             "II",
             "IJ",
             "IK",
             "IL",
             "IM",
             "IN",
             "IO",
             "IP",
             "IQ",
             "IR",
             "IS",
             "IT",
             "IU",
             "IV",
             "IW",
             "IX",
             "IY",
             "IZ",
             "JA",
             "JB",
             "JC",
             "JD",
             "JE",
             "JF",
             "JG",
             "JH",
             "JI",
             "JJ",
             "JK",
             "JL",
             "JM",
             "JN",
             "JO",
             "JP",
             "JQ",
             ]

def readSpss():
    with savReaderWriter.SavReader(filepath, ioUtf8=True) as read:
        ret = read.getSavFileInfo()
        return ret[4], ret[2], ret[5], ret[6]

def vbaStr(totalStr, sum, readSpss):
    formats, varnames, varLabels, valueLabels = readSpss()
    for i in range(len(varnames)):

        if varnames[i] in valueLabels:

            subvalueLables = {}
            for j in valueLabels[varnames[i]]:
                subvalueLables[int(j)] = valueLabels[varnames[i]][j]

            # totalStr += a + excelList[i] + ":" + excelList[i] + b
            for zz in subvalueLables:
                totalStr += a + excelList[i] + ":" + excelList[i] + b
                totalStr += c + subvalueLables[zz] + d + subvalueLables[zz] + e + str(zz) + f
                totalStr += g
                sum += 1
                totalStr += "\n************hello************\n\n"
            # totalStr += g
            totalStr += "=============================\n\n"

        else:
            continue
    return totalStr, sum

totalStr, sum = vbaStr(totalStr, sum, readSpss)

print(totalStr)

print(sum)

用Python在执行vba命令方法,有点类似执行shell的形式,但必须在windows环境下面执行,不能在linux下面

注意问题:

  1. 必须另存为xlsm文件格式

  2. 第二,在执行Python脚本的时候必须是打开excel的

  3. 必须新建模块(vba中)

  4. vba代码必须有函数

  5. office必须开启宏,否则不生效  6. 打开vba快捷键alt + f11

最后看代码

vba代码

Sub test()    《============这个函数很重要,对应着python
Dim m
m = 1
Columns("G:G").Select
m = 1
On Error GoTo Err_Handle

For m = 1 To 65
Selection.Find(What:="男", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, MatchByte:=False, SearchFormat:=False).Activate
ActiveCell.Replace What:="男", Replacement:="1", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next m

Exit Sub
Err_Handle:
End Sub

python代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import win32com.client

filename = "C:/Users/Administrator/Desktop/test.xlsm"
xls = win32com.client.Dispatch(‘Excel.Application‘)
xls.Workbooks.Open(Filename=filename)
xls.DisplayAlerts = 0
xls.Run("test1")
时间: 2024-11-06 20:49:29

用python批量执行VBA代码的相关文章

python批量执行paramiko

puppet 分发软件  同步文件 ssh-批量执行-paramiko-比较好的模块 直接修改远端主机的host文件 python批量执行paramiko,布布扣,bubuko.com

PowerPoint2007 执行VBA代码'.Shapes(ShapeIdx).Chart' 报438错误 不知道该对象或方法

因为之前木有这个问题的 重装了下Office就出现这个问题了 百度木有百到 然后看到一位仁兄这样说: 我想是不是微软不给力 需要打补丁 于是安装了下面补丁 果然好了: PowerPoint2007 执行VBA代码'.Shapes(ShapeIdx).Chart' 报438错误 不知道该对象或方法

pyv8的安装和使用:python中执行js代码

pyv8 的作用是在python中执行js代码,然后可以使用js里的变量等内容.python取得javascript里面的值.javascript取得python里面的值.python和javascript里面的函数交互 mac下的安装:pip install -e git://github.com/brokenseal/PyV8-OS-X#egg=pyv8 安装后有两个文件:一个PyV8.py  另一个_PyV8.so 下面示例是执行js文件 from pyv8 import PyV8 ctx

python 批量执行脚本(服务端和客户端建立TCP连接)

有很多开源的批量部署的工具可以使用,比如puppet, ansible , saltstack , chef . 但这些工具都有自己的一套语法规则,你得按照他的语法来编写程序,然后批量执行. 那有没有方法可以直接写bash 或者Python脚本,然后批量执行呢? 方法当然是有的,需要自己写程序来传输脚本,拷贝文件,再复杂点,可以自定义脚本式同步还是异步执行,自定义要执行的主机组,等等,需要根据自己的业务需要来想. 这里只是抛砖引玉,我采用建立socket(TCP)连接来批量执行脚本. 服务端脚本

python批量执行命令发送文件

#!/usr/bin/python #-*- coding: utf-8 -*- import paramiko import datetime import os,tab,sys from multiprocessing import Process, Pool host_list = ( ('192.168.1.127','root','123456'), ('192.168.1.137','root','123456'), ('192.168.1.143','root','123456')

Python批量执行oracle中的insert语句

从oracle导出一个表的数据,导出的格式是insert语句,数据量30万. 直接在PL/SQL Developer中执行,速度非常慢,脚本中也是100条数据提交一次.因为需要的时间太长,每次中断后,下次执行,又要重新全部导入,需要把之前导入的数据清除. 为了能够断点续传,想了个办法: 用Python把脚本分拆,用commit作为分隔符(脚本中每100条数据有一个commit),分拆成多个脚本,用Python遍历文件夹下的脚本,分别执行每个脚本的语句,执行完成后,把脚本移动到BAK目录,这样即使

python批量执行脚本,使用unittest.TestSuit(); unittest.TextTestRunner().run(); addTest();unittest.defaultTestLoader.discover();

#alltest.py中内容如下import unittest,osdef all(): #path="D:\\study\\python_api_test\\test1203" #手动添加路径 path=os.getcwd() #获取路径 files=unittest.defaultTestLoader.discover(path, pattern="hui*.py", top_level_dir=None) lastall=unittest.TestSuite(

python接口自动化(二十六)--批量执行用例 discover(详解)

简介 我们在写用例的时候,单个脚本的用例好执行,那么多个脚本的时候,如何批量执行呢?这时候就需要用到 unittest 里面的 discover 方法来加载用例了.加载用例后,用 unittest 里面的 TextTestRunner 这里类的 run 方法去一次执行多个脚 本的用例.那么前边介绍那么多都是半道开始,半道出家,这篇就带大家从头到尾,一步一步给小伙伴们详细介绍一下. 新建测试项目 1.pycharm 左上角 File>New Projetc>Pure Python,在 locat

Python脚本远程批量执行命令

摘要 本文主要写用python脚本远程连接多台服务器,然后批量执行命令,最终返回命令执行结果. 这个可以说是Ansible,Puppet等工具的最简单的雏形. 做运维的同学应该都知道的. 正文 multi_task.py #_*_coding:utf-8_*_ import  multiprocessing import paramiko import getpass import ConfigParser class MultiTask(object):     '''handles all