Vba 如何在运行保存宏后停止重命名Excel工作表
下面是一个宏,用于将多个工作表保存到不同的csv文件,但它会不断重命名和保存原始工作簿,以及如何停止此操作Vba 如何在运行保存宏后停止重命名Excel工作表,vba,excel,Vba,Excel,下面是一个宏,用于将多个工作表保存到不同的csv文件,但它会不断重命名和保存原始工作簿,以及如何停止此操作 Private Sub CommandButton1_Click() Dim WS As Excel.Worksheet Dim SaveToDirectory As String Dim CurrentWorkbook As String Dim CurrentFormat As Long Dim myName As String myName = myName & Appl
Private Sub CommandButton1_Click()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
Dim myName As String
myName = myName & Application.Cells(2, 2) 'cell B2 '
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook '
SaveToDirectory = "C:\temp\"
'此行用于更正Stackoverflow代码格式中的斜杠问题
For Each WS In ThisWorkbook.Worksheets
WS.SaveAs SaveToDirectory & myName & WS.Name, xlCSV
Next
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = False
' Temporarily turn alerts off to prevent the user being prompted '
' about overwriting the original file. '
End Sub
ActiveWorkbook.SaveAs文件名:=当前工作簿,文件格式:=当前格式应用程序。显示警报=错误
如果您没有在工作簿上写入任何内容,为什么要保存它?请尝试以下操作:
Private Sub CommandButton1_Click()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim myName As String
Dim CurrentWorkbook As String
' Get the path to the curent workbook so we can open it later.
CurrentWorkbook = ThisWorkbook.FullName
SaveToDirectory = "C:\temp\"
' Turn off Excel alerts so we're not prompted if the file already exists.
Application.DisplayAlerts = False
For Each WS In ThisWorkbook.Worksheets
WS.Activate ' Make this the current worksheet.
myName = Application.Cells(2, 2) ' Get the contents of cell B2 for our file name.
WS.SaveAs SaveToDirectory & myName & WS.Name, xlCSV
Next
' Open the original workbook.
Application.Workbooks.Open CurrentWorkbook
' Close workbook associated with the last saved worksheet.
ThisWorkbook.Close xlDoNotSaveChanges
End Sub
Excel SaveAs方法似乎使保存的工作表成为活动工作簿,因此我只需关闭它而不保存。您能正确设置代码格式吗?这真的很难读。嗨,帕特里克。我复制了您的宏,似乎出现了运行时错误1004,对象“\u工作表”的方法“SaveAs”失败。我能帮忙吗?这太奇怪了;你的代码和我的代码几乎没有区别。确保粘贴正确。另外,将SaveToDirectory更改为“C:\temp\”。祝大家新年快乐。愿新年带给大家健康和财富。嗨,帕特里克。粘贴了整个代码,并不断收到相同的错误消息。我还将目录更改为c:\temp。这是Excel 2003与SP3的常见问题吗?。提前谢谢你。约翰,我不能再制造你的问题了;我的代码很好用。你的宏观安全性是什么?试着把它放低,看看是否有帮助。还要检查运行宏的用户是否具有C:\temp的写入权限。另外,尝试在调用SaveAs时将“xlCSV”替换为“6”。好的,我只是通过将SaveToDirectory变量更改为不存在的路径(D:\temp)来重新创建问题。我认为您保存到的路径无效,或者您没有写入权限。目的是将每个工作表保存到工作簿中的单独csv文件中。非常感谢。