简体   繁体   English

按钮(表单控件)运行宏不正确

[英]Button (form control) runs Macro incorrectly

I've created a macro to export several tabs of a spreadsheet to csv files, then reopen the original document.我创建了一个宏来将电子表格的多个选项卡导出到 csv 文件,然后重新打开原始文档。 Normally the macro runs correctly, however when run through a button it fails to find other sheets in the workbook.通常宏运行正确,但是当通过按钮运行时,它无法在工作簿中找到其他工作表。

The document contains 5 tabs: 1 for the button, and 4 for the data (hardcoded below).该文档包含 5 个选项卡:1 个用于按钮,4 个用于数据(下面是硬编码)。 When I run the macro, it exports the 4 sheets correctly but when I press the button, it exports the first sheet 4 times (the one containing the button, not listed in the macro).当我运行宏时,它会正确导出 4 张工作表,但是当我按下按钮时,它会导出第一张工作表 4 次(包含按钮的工作表,未在宏中列出)。 All I can think is that the button is failing to pass the active workbook to the macro, and therefore it cannot "see" the Worksheets object...is there something I can do to fix this?我能想到的只是按钮无法将活动工作簿传递给宏,因此它无法“看到”工作表 object ......我可以做些什么来解决这个问题?

Note that all lines other than the SaveAs commands are (theoretically) unrelated.请注意,除了 SaveAs 命令之外的所有行(理论上)都是不相关的。 I have tried replacing "Worksheets" with "ActiveWorkbook.Worksheets" and gotten the same result.我尝试用“ActiveWorkbook.Worksheets”替换“Worksheets”并得到相同的结果。

Sub SaveAsCSVs()

Dim fullname As String
fullname = ThisWorkbook.fullname

Application.DisplayAlerts = False
Worksheets("Ships").SaveAs Filename:=ThisWorkbook.path & "\ships", FileFormat:=xlCSV
Worksheets("Weapons").SaveAs Filename:=ThisWorkbook.path & "\weapons", FileFormat:=xlCSV
Worksheets("Specials").SaveAs Filename:=ThisWorkbook.path & "\specials", FileFormat:=xlCSV
Worksheets("Modifiers").SaveAs Filename:=ThisWorkbook.path & "\modifiers", FileFormat:=xlCSV
Application.Workbooks.Open (fullname)
Application.DisplayAlerts = True
Workbooks("modifiers.csv").Close

End Sub

Strange, behavior, indeed...奇怪,行为,确实……

Being a single sheet to be saved, please use the next adapted code.作为要保存的单张,请使用下一个改编代码。 It should work in both cases:它应该在两种情况下都有效:

Sub SaveAsCSVs()
 Dim fullname As String
 fullname = ThisWorkbook.fullname

Application.DisplayAlerts = False
Worksheets("Ships").Copy 'it creates a new workbook containing only the copied sheet...
   ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\ships", FileFormat:=xlCSV
   ActiveWorkbook.Close False
Worksheets("Weapons").Copy
  ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\weapons", FileFormat:=xlCSV
  ActiveWorkbook.Close False
Worksheets("Specials").Copy
  ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\specials", FileFormat:=xlCSV
  ActiveWorkbook.Close False
Worksheets("Modifiers").Copy
  ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\modifiers", FileFormat:=xlCSV
  ActiveWorkbook.Close False
'Application.Workbooks.Open (fullname) 'no need to open, it remained opened...
Application.DisplayAlerts = True
End Sub

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

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