使用Python的Command Line操作Excel的Macro

目的:对Office的VBA进行Command Line式的批处理。

环境:Window XP、Python 2.5、Excel 2003

步骤:

Step1: 新建待试验Excel文件。确认Excel的安全级别非“高”,确保Excel的宏可以运行。在VBE环境下,插入一个模块Module1(或者在Sheet操作区域中插入Public的Sub),保存Excel,命名为testExcel.xls,退出。代码如下:

Sub  PythonToExcel()

       
Dim  finalRow  as   Integer
       
       finalRow
= Range( " A6635 " ).End(xlup).Row
      
       Sheets(
1 ).Cells(finalRow, 1 ) = " Log Time "   &   "  :  "   &   Now ()

End Sub

Step2:使用Phython IDE,在测试目录下新建调用Excel的脚本程序,保存Python程序,命名为testPython.py,Debug,Run Module,退出。代码(改编自http://www.windowsdevcenter.com/pub/a/windows/2005/03/22/word_macros.html#picking_scripting_language)如下:

#  batchmacro.py
#
 Python script for batch running Word macros

import  sys
import  os
import  glob
from  win32com.client  import  Dispatch

#  Launch new instance of Word
wb  =  Dispatch( ' Excel.Application ' )
wb.Visible 
=   1

#  First argument to script is the name of the macro
macro_to_run  =  sys.argv[ 1 ]

#  Everything else is a document on which to run macro
for  arg  in  sys.argv[ 2 :]:
    
#  Expand any wildcards that might be in the argument
     for  file  in  glob.glob(arg):
      doc 
=  wb.Workbooks.Open(os.path.abspath(file))
      wb.Run(macro_to_run)
      doc.Save()
      doc.Close()
wb.Quit()

Step3:cmd-〉进入你的Python目录-〉键入命令

python your  path / testPython . py PythonToExcel * . doc

结果:Python脚本处理了Office文档。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值