Export each sheet to a separate csv file

后端 未结 2 1320

I need to programmaticaly via a VBA/VBS script export all worksheets (4 in total and I know the names) to worksheet named csv files in the same folder, without loading excel

相关标签:
2条回答
  • 2020-11-27 07:59

    A vbs to run this code would look something like this.

    1. The vbs file can be executed from the commandline
    2. The folder name is redundant as if the file exists (the FSO object tests for this) then the folder it resides in must also exist
    3. The code automates Excel to separate the sheets

    two key points to note compared to your VBA above

    • you can't Dim a vbs object as a string, Workbook etc (hence your initial error). You can only Dim them
    • you can't used a named constant such as xlCSV in vbscript, hence the use of 6 below as the CSV format

      Dim strFilename  
      Dim objFSO  
      Set objFSO = CreateObject("scripting.filesystemobject")  
      strFilename = "C:\temp\test.xlsx"  
      If objFSO.fileexists(strFilename) Then  
        Call Writefile(strFilename)  
      Else  
        wscript.echo "no such file!"  
      End If  
      Set objFSO = Nothing  
      
      Sub Writefile(ByVal strFilename)  
      Dim objExcel  
      Dim objWB  
      Dim objws  
      
      Set objExcel = CreateObject("Excel.Application")  
      Set objWB = objExcel.Workbooks.Open(strFilename)  
      
      For Each objws In objWB.Sheets  
        objws.Copy  
        objExcel.ActiveWorkbook.SaveAs objWB.Path & "\" & objws.Name & ".csv", 6  
        objExcel.ActiveWorkbook.Close False  
      Next 
      
      objWB.Close False  
      objExcel.Quit  
      Set objExcel = Nothing  
      End Sub  
      
    0 讨论(0)
  • 2020-11-27 08:02

    To get you started:

    Given an Excel workbook containing a sheet Demo like

    -------------------------------
    SELECT * FROM Demo
    -------------------------------
    |F1|F2 |F3        |F4        |
    | 1|1.1|12/10/2011|text elm 1|
    | 2|2.2|12/11/2011|text elm 2|
    | 3|4.4|12/12/2011|text elm 3|
    -------------------------------
    

    and an ADODB.Connection with a ConnectionString like:

    Provider=MSDASQL.1;Extended Properties="DBQ=<FullPathToYourXls>;Driver={Microsoft
     Excel Driver (*.xls)};
    

    all you need to .Execute is a SELECT INTO statement like

    SELECT * INTO [Demo.csv] IN '<PathToYourCsvFolder>' 'Text;' FROM Demo
    

    to get:

    type ..\data\ExcelCsv2\Demo.csv
    "F1";"F2";"F3";"F4"
    1;1,10;10.12.2011 00:00:00;"text elm 1"
    2;2,20;11.12.2011 00:00:00;"text elm 2"
    3;4,40;12.12.2011 00:00:00;"text elm 3"
    

    (german locale)

    The SELECT INTO statement will create the appropriate section

    [Demo.csv]
    ColNameHeader=True
    CharacterSet=1252
    Format=Delimited(;)
    Col1=F1 Integer
    Col2=F2 Float
    Col3=F3 Date
    Col4=F4 Char Width 50
    

    in the schema.ini file automagically.

    0 讨论(0)
提交回复
热议问题