运行保存macros后如何停止重命名excelsheets

下面是一个macros保存多个表到不同的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 & 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 Filename:=CurrentWorkbook, FileFormat:=CurrentFormat Application.DisplayAlerts = False

如果你没有在工作簿上写任何东西,你为什么要保存它?

尝试这个:

 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方法使保存的工作表成为活动工作簿,所以我只是closures它而不保存。