我正在从python运行一个脚本,它运行良好,只是我注意到宏没有排序,除非我从excel调用子。当它从python调用时,它只是跳过排序行。我尝试激活工作表或从工作表调用sort,但没有任何效果。
同样,当我直接从excel打开脚本时,它可以工作并排序,但当从python调用时,它会运行,但范围没有排序属性。
我试图使用指定的范围";B5:E74694";但当我这样做的时候,它说不能得到范围类的排序属性。
当从外部应用程序调用时,对象是否没有所有的方法?
Dim Array_Prices As Variant, i As Long
Dim Range_Prices As Range, Row_Last As Long
Row_Last = Sht_History.Cells(Sht_History.Rows.Count,2).End(xlUp).Row
If Sht_History.AutoFilterMode = True Then
Sht_History.AutoFilterMode = False
Sht_History.Activate
Set Range_Prices = Sht_History.Range("B5:E" & Row_Last)
Range_Prices.Sort key1:=Range_Prices.Cells(1, 1), order1:=xlDescending, key2:=Range_Prices.Cells(1, 2), order2:=xlAscending, Header:=xlYes
以下是运行的python代码,然后VBA代码由Workbook_BeforClose事件触发
excelapp = win32.Dispatch('Excel.Application')
excelapp.Visible = True
excelapp.DisplayAlerts = False
wb_strip = excelapp.Workbooks.Open(path_wb_strip, False, False
wb_strip.Close(True)
excelapp.Quit()
正如您所说的vba工作良好,当从Excel调用时,我将重点关注Python部分。
关于Python脚本的一些评论:
-
您似乎没有从python脚本中运行宏(记得添加丢失的信息并删除
[]
(:xl.Application.Run('[your_workbook_name].xlsm![Module_name].[our_macro_name]')
-
请记住导入
import win32com.client
。如果未安装:pip install pywin32
REF -
使用
del
方法删除脚本末尾的excel应用程序实例 -
这可能是不言自明的,但如果您使用
path_wb_strip
,请记住在代码开头为其赋值
例如:path_wb_strip = 'C:Usersworkbook.xlsm'
示例
下面的例子来自pythoninoffice.com。它适用于我的测试脚本——只更新名称和路径。
import win32com.client #see comment 1
xl = win32com.client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open(r'C:Usersworkbook.xlsm') #your path_wb_strip
xl.Application.Run('workbook.xlsm!Module1.my_macro') #comment 2
wb.Save()
xl.Application.Quit()
del xl #comment 3