VBA Excel file to CSV, keeps CSV filename same as original workbook

前端 未结 3 1854
鱼传尺愫
鱼传尺愫 2021-01-27 15:36

I am trying to find a fast way to save my xlsx files as csv files with the same file-name as the xlsx file (just in csv forma

3条回答
  •  离开以前
    2021-01-27 16:18

    I would organize the pieces before stitching them together with standard string concatenation. Here is the relevant section of the code using the InStr function.

    Dim myPath As String, myFileName As String
    
    myPath = "C:\Users\paddy\Desktop\NEW CSV files whole CGM date ok!"
    'possible alternate that gets the environment variable USERNAME
    'myPath = "C:\Users\" & Environ("USERNAME") & "\Desktop\NEW CSV files whole CGM date ok!"
    
    'check if the folder exists and if not create it
    If Not CBool(Len(Dir(myPath, vbDirectory))) Then _
        MkDir Path:=myPath
    
    
    myFileName = Left(ActiveWorkbook.Name, InStr(1, ActiveWorkbook.Name, ".xl", vbTextCompare) - 1)
    'you don't actually need .csv as the extension if you are explicitly saving as xlCSV or xlCSVMac but here is an alternate
    'myFileName = Left(ActiveWorkbook.Name, InStr(1, ActiveWorkbook.Name, ".xl", vbTextCompare) - 1) & ".csv"
    
    'output to the VBE's Immediate window for checking later in case there is a problem
    Debug.Print myPath & Chr(92) & myFileName
    
    ' the backslash is ASCII character 92
    ActiveWorkbook.SaveAs Filename:=myPath & Chr(92) & myFileName, _
        FileFormat:=xlCSVMac, CreateBackup:=False
    

    I'm not sure what all the scrolling was doing; it probably isn't necessary. You might want to add in the number formatting command.

提交回复
热议问题