简体   繁体   English

为什么Excel宏在Excel中起作用,但从Python调用时却不能起作用?

[英]Why does Excel macro work in Excel but not when called from Python?

I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. 我有一个Excel宏,它可以删除工作表,复制另一个工作表并将其重命名为与已删除工作表相同的名称。 This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message: 从Excel运行时,这很好用,但是当我通过从Python调用宏来运行它时,出现以下错误消息:

Run-time error '1004' - Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by VisualBasic. 运行时错误'1004'-无法将工作表重命名为与另一个工作表,被引用的对象库或VisualBasic所引用的工作簿相同的名称。

The macro has code like the following: 宏具有如下代码:

Sheets("CC").Delete
ActiveWindow.View = xlPageBreakPreview
Sheets("FY").Copy After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = "CC"

and the debugger highlights the error on the last line where the sheet is renamed. 调试器会在重命名工作表的最后一行突出显示错误。 I've also tried putting these calls directly in python but get the same error message. 我也尝试将这些调用直接放在python中,但得到相同的错误消息。

Any suggestions are much appreciated! 任何建议,不胜感激!

Thanks. 谢谢。

I ran the code inside Excel VBA. 我在Excel VBA中运行了代码。
I am guessing that the following line is failing. 我猜下面的行失败了。

Sheets("CC").Delete

And that is the reason, you can't give the new sheet same name as existing (non-deleted) sheet. 这就是原因,您不能为新工作表提供与现有(未删除)工作表相同的名称。

Put Application.DisplayAlerts = False before Sheets("CC").Delete and Sheets("CC").Delete之前放置Application.DisplayAlerts = False Sheets("CC").Delete
Application.DisplayAlerts = True once you are finished with the code. 完成代码后, Application.DisplayAlerts = True

I haven't used python but it seems the library is swallowing that error for you and letting you go ahead to the next statement. 我没有使用过python,但似乎该库正在为您吞下该错误,并让您继续执行下一条语句。

Hope that helps. 希望能有所帮助。

Behind the scenes, VB and VBA are maintaining references to COM objects for the application, worksheets etc. This is why you have the globals 'Application', 'Worksheets' etc. It is possible that VBA is still holding a reference to the worksheet, so Excel hasn't tidied it up properly. 在后台,VB和VBA维护着对应用程序,工作表等COM对象的引用。这就是为什么拥有全局“应用程序”,“工作表”等的原因。VBA可能仍在保留对工作表的引用,因此Excel尚未正确整理。

Try not using these implicit globals and referencing the items in the object model explicitly. 尝试不使用这些隐式全局变量,并明确引用对象模型中的项目。 Alternatively you could do it directly in Python. 或者,您可以直接在Python中执行此操作。

Here's a python script that will do something like what you want: 这是一个python脚本,它将执行您想要的操作:

import win32com.client
xl = win32com.client.Dispatch ('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Add()
wb.Worksheets[0].Delete()
wb.Worksheets.Add()
wb.Worksheets[0].Name = 'Sheet1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM