簡體   English   中英

VBA:將xls轉換為csv並將其保存在特定路徑中

[英]VBA: convert xls to csv and save it in a certain path

請幫我。 我正在嘗試將放置在服務器(例如one \\ test \\ 1.xls)文件上某個路徑上的.xls / .xlsx轉換為.csv(不破壞日期格式或任何其他信息)並將其保存在固定路徑(比方說一個\\結果\\ 1.csv)。 此過程必須每24小時自動重復一次。

謝謝!

到目前為止,我只得到下面的代碼,該代碼僅轉換為csv並將其保存在與原始文件相同的位置。
同樣由於某種未知原因,它會將日期的一半轉換為例如05/31/2017(原始格式為31.05.2017)。

Sub ConvertXLSToCSV()

    Dim InputPath As String

    Dim PowershellCommand As String



    ' To suppress excel prompts and alert messages while the macro is running.

    Application.DisplayAlerts = False

    Do

        ' Taking the input excel file path which needs to be converted to .csv format.

        InputPath = InputBox("Enter the full path of the input excel file.", "Convert XLS to CSV")

        If Trim(InputPath) <> "" Then

            If Dir(InputPath) = vbNullString Then

                MsgBox "File: '" & InputPath & "' doesn't exists.", vbOKOnly + vbCritical, "Convert XLS to CSV"

            ElseIf Split(Dir(InputPath), ".")(1) = "xlsx" Or Split(Dir(InputPath), ".")(1) = "xls" Then

                InputPath = Trim(InputPath)

                ' Opening the input excel file and saving it in .csv using powershell.

                PowershellCommand = "$ExcelWB = new-object -comobject excel.application" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB = new-object -comobject excel.application" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB.Visible = $false" & vbNewLine & "$ExcelWB.DisplayAlerts = $false" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook = $ExcelWB.Workbooks.Open('" & InputPath & "')" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook.SaveAs('" & Left(InputPath, (InStrRev(InputPath, ".", -1, vbTextCompare) - 1)) & ".csv',6)" & vbNewLine

                PowershellCommand = PowershellCommand & "$Workbook.Close($false)" & vbNewLine

                PowershellCommand = PowershellCommand & "$ExcelWB.quit()" & vbNewLine

                PowershellCommand = "Powershell.exe -command " & PowershellCommand

                Set WshShell = CreateObject("WScript.Shell")

                WshShell.Exec (PowershellCommand)

                Exit Do

            Else:

                MsgBox "Input file is not in excel (.xlsx/.xls) format.", vbOKOnly + vbCritical, "Convert XLS to CSV"

            End If

        ElseIf StrPtr(InputPath) <> 0 Then MsgBox "Please enter the full path of the input excel file.", vbOKOnly + vbExclamation, "Convert XLS to CSV"

        End If

    Loop Until StrPtr(InputPath) = 0

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM