VBA to create new sheet with file name using save dialogue box and save as CSV format

a 夏天 提交于 2019-12-12 03:44:46

问题


My requirement is that I am having a sheet with some data and a button which has to perform below said task.

Task is that once button is clicked it has to ask for file name and location to be save to the new sheet in csv format and the data in the active sheet has to be copied and pasted in a new sheet and name of new sheet should be the name given for file to save in CSV format.

Can anyone please help on this?


回答1:


This should do the trick, edit to taste. Save the macro to a new module, then add a button Developer Tab > Insert > Button. Assign the button to this macro.

Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook

'Change the path, must end with \
SaveToDirectory = "C:\Users\username\Documents\test\"
For Each WS In ThisWorkbook.Worksheets
    Sheets(WS.Name).Copy
    ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV
    ActiveWorkbook.Close savechanges:=False
    ThisWorkbook.Activate
Next
'edit/remove the for loop to suit
End Sub

Credit where credit is due. Adapted from this answer: Saving excel worksheet to CSV files with filename+worksheet name using VB



来源:https://stackoverflow.com/questions/43376774/vba-to-create-new-sheet-with-file-name-using-save-dialogue-box-and-save-as-csv-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!