简体   繁体   中英

How to save a worksheet in Excel to CSV using VBA and file saved as User's name and Date?

Hello and hi everyone.

I'm sorry if what I asked right now sounds dumb or stupid, but I'm relatively new to VBA's and not really fluent with it.

Now, I have a form for user to input report on incident happened at their workplace and I manage to save the Data worksheet as csv but now, I want to automatically save the sheet as username and time the csv printed.

Here is what my code look like.

Public Sub ExportWorksheetAndSaveAsCSV()

Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Dim xStrDate As String


Set shtToExport = ThisWorkbook.Worksheets("PartsData")
xStrDate = Format(Now, "yyyy-mm-dd hh-mm-ss")
Set wbkExport = Application.Workbooks.Add

shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False

wbkExport.SaveAs FileName:=xStrDate,"C:\temp\IncidentDatabase.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True

wbkExport.Close SaveChanges:=False

End Sub

and when I try to run the code, this happened

在此处输入图片说明

it's highlighted on this part -

wbkExport.SaveAs FileName:=xStrDate,"C:\temp\IncidentDatabase.csv", FileFormat:=xlCSV

I have read some of almost similar question but found no answer. Please help me. Thank you. Regard.

Copy the worksheet without providing a location. This creates a new workbook with the copied worksheet as the only worksheet.

The ENVIRON function can retrieve environment variables like the user name.

Public Sub ExportWorksheetAndSaveAsCSV()

    Dim fn As String

    fn = environ("USERNAME") & "-" & Format(Now, "yyyy-mm-dd hh-mm-ss")

    ThisWorkbook.Worksheets("PartsData").Copy

    With activeworkbook
        Application.DisplayAlerts = false
        .SaveAs FileName:="C:\temp\" & fn, FileFormat:=xlCSV
        Application.DisplayAlerts = true
        .close savechanges:=false
    end with

End Sub

Please see .SaveAs properties here .

The first argument is the name & the second is the file type.

Dim loc As String
loc = "C:\temp\"
xStrDate = Format(Now, "yyyy-mm-dd hh-mm-ss")

wbkExport.SaveAs loc & wbkExport.Name &  xStrDate, xlCSV

I think code line

wbkExport.SaveAs FileName:=xStrDate,"C:\temp\IncidentDatabase.csv", FileFormat:=xlCSV 

should be changed to

 wbkExport.SaveAs FileName:="C:\temp\IncidentDatabase - " & xStrDate & ".csv", FileFormat:=xlCSV

for proper working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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