【问题标题】:VBA: convert xls to csv and save it in a certain pathVBA:将xls转换为csv并将其保存在某个路径中
【发布时间】:2017-06-07 08:27:10
【问题描述】:

请帮助我。 我正在尝试将放置在服务器上某个路径上的 .xls/.xlsx(比如说 one\test\1.xls)文件转换为 .csv(不会损坏日期格式或任何其他信息)并将其保存在一个固定的路径(比如说一个\result\1.csv)。此过程必须每 24 小时自动重复一次。

谢谢!

【问题讨论】:

  • 您能否向我们展示您目前拥有的代码并具体指出您遇到的问题?是另存为吗?是文件格式吗?是自动化吗?现在你的问题太宽泛了,因为你没有显示任何代码并询问三个不同的方面。

标签: excel vba


【解决方案1】:

到目前为止,我只得到了下面的代码,它只转换为 csv 并将其保存在与原始文件相同的位置。
同样由于某些未知原因,它会将日期的一半转换为 2017 年 5 月 31 日,例如(原始格式为 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

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 2017-04-18
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    相关资源
    最近更新 更多