先说下背景环境

  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下面

注意问题:

  . 必须另存为xlsm文件格式

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

  . 必须新建模块(vba中)

  . vba代码必须有函数

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

最后看代码

vba代码

Sub test()    《============这个函数很重要,对应着python
Dim m
m =
Columns("G:G").Select
m =
On Error GoTo Err_Handle For m = To
Selection.Find(What:="男", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, MatchByte:=False, SearchFormat:=False).Activate
ActiveCell.Replace What:="男", Replacement:="", 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- -*- import win32com.client filename = "C:/Users/Administrator/Desktop/test.xlsm"
xls = win32com.client.Dispatch('Excel.Application')
xls.Workbooks.Open(Filename=filename)
xls.DisplayAlerts =
xls.Run("test1")

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

  1. python中执行javascript代码

    python中执行javascript代码: 1.安装相应的库,我使用的是PyV8 2.import PyV8 ctxt = PyV8.JSContext()     ctxt.enter()     ...

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

    pyv8 的作用是在python中执行js代码,然后可以使用js里的变量等内容.python取得javascript里面的值.javascript取得python里面的值.python和javascr ...

  3. Python批量执行oracle中的insert语句

    从oracle导出一个表的数据,导出的格式是insert语句,数据量30万. 直接在PL/SQL Developer中执行,速度非常慢,脚本中也是100条数据提交一次.因为需要的时间太长,每次中断后, ...

  4. python批量执行shell命令

    [root@master ~]# cat a.py #!/usr/bin/python # -*- coding:UTF- -*- import subprocess def fun(): subpr ...

  5. python爬虫执行js代码-execjs

    一.安装模块 pip install PyExecJS execjs会自动使用当前电脑上的运行时环境(建议用nodejs,与Phantomjs) 二.简单的使用 import execjs js_ob ...

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

    #alltest.py中内容如下import unittest,osdef all(): #path="D:\\study\\python_api_test\\test1203" ...

  7. web自动化测试实战之批量执行测试用例

    01实战之分离测试固件 在UI 自动化测试中,不管编写哪个模块的测试用例,都需要首先在测试类中编写测试固件初始化WebDriver类及打开浏览器,执行登录,才能进行下一步业务逻辑的操作,测试用例执行完 ...

  8. Python 中使用 ddt 来进行数据驱动,批量执行用例,修改ddt代码

    1. 什么是数据驱动? 使用数据驱动有什么好处? 用例执行是靠数据来驱动的,每条测试用例除了测试数据不一样意外,所有的用例代码都是一样的,为了使用例批量执行,我们会使用数据驱动的思想来批量执行测试用例 ...

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

    简介 我们在写用例的时候,单个脚本的用例好执行,那么多个脚本的时候,如何批量执行呢?这时候就需要用到 unittest 里面的 discover 方法来加载用例了.加载用例后,用 unittest 里 ...

随机推荐

  1. React.Fragment 的作用:代替div作为外层

    https://segmentfault.com/a/1190000013220508 import React, { Fragment } from 'react'; <Fragment> ...

  2. 由于CentOS的系统安装了epel-release-latest-7.noarch.rpm 导致在使用yum命令时出现Error: xz compression not available问题

    由于CentOS6的系统安装了epel-release-latest-7.noarch.rpm 导致在使用yum命令时出现Error: xz compression not available问题.解 ...

  3. unity c# script error CS0664: Literal of type double cannot be implicitly converted to type `float'. Add suffix `f' to create a literal of this type

    例如在unity c# script中定义 private float x=0.0; 则会报 error CS0664: Literal of type double cannot be implic ...

  4. SpringCloud分布式开发五大神兽

    SpringCloud分布式开发五大神兽 服务发现——Netflix Eureka 客服端负载均衡——Netflix Ribbon 断路器——Netflix Hystrix 服务网关——Netflix ...

  5. STORM在线业务实践-集群空闲CPU飙高问题排查(转)

    最近将公司的在线业务迁移到Storm集群上,上线后遇到低峰期CPU耗费严重的情况.在解决问题的过程中深入了解了storm的内部实现原理,并且解决了一个storm0.9-0.10版本一直存在的严重bug ...

  6. 在 Windows 8 中启用可匿名访问的共享

    就是不用输入用户名和密码,直接通过网上邻居可以访问的共享. 1.打开本地组策略编辑器(快捷键Win+R,打开运行,输入gpedit.msc,确定): 2.打开:"本地计算机策略->计算 ...

  7. FPGA基础设计(四):IIC协议

    很多数字传感器.数字控制的芯片(DDS.串行ADC.串行DAC)都是通过IIC总线来和控制器通信的.不过IIC协议仍然是一种慢速的通信方式,标准IIC速率为100kbit/s,快速模式速率为400kb ...

  8. 【Android】7.5 RelativeLayout(相对布局)

    分类:C#.Android.VS2015: 创建日期:2016-02-11 一.简介 RelativeLayout是一种相对布局,容器中子元素的位置是相对于其前一个元素或者其他元素的位置来计算的,或者 ...

  9. How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop?

    Scala List/sequence FAQ: How do I iterate over a Scala List (or more generally, a sequence) using th ...

  10. AngularJS实现跨域请求

    跨域,前端开发中经常遇到的问题,AngularJS实现跨域方式类似于Ajax,使用CORS机制. 下面阐述一下AngularJS中使用$http实现跨域请求数据. AngularJS XMLHttpR ...