Visual Basic代码循环遍历文件夹并将.csv文件转换为.txt文件

时间:2018-09-01 17:32:35

标签: vba loops csv text type-conversion

你好,正如标题所述,我需要一个Visual Basic代码,该代码循环遍历一个文件夹并搜索,csv,然后将CSV文件转换为文本文件,我发现了此代码,但仅适用于一个文件:

Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objFile : Set objFile = objFSO.OpenTextFile("c:\yourfolder\conv.csv")
Dim objOut : Set objOut = objFSO.CreateTextFile("C:\yourfolder\new_conv.csv")

arrData = objFile.ReadAll
objOut.Write Replace(arrData,",",vbTab)
objFile.Close
objOut.Close

1 个答案:

答案 0 :(得分:0)

这是一个粗略的想法,即相对于您的代码而言,将其转换为使用其他子代码看起来像什么。可以肯定的是,有更好的方法可以写,但这类似于您的代码。例如,一种改进是将其实现为具有convert方法的类,而不是传递引用。

您可能还想实现清理例程以删除csv?

Option Explicit
Public Sub test()
    Dim objFSO As Object, objFile As Object, folder As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set folder = objFSO.GetFolder("C:\Users\User\Desktop\TestFolder")

    For Each objFile In folder.Files
        If objFSO.GetExtensionName(objFile) = "csv" Then
            CreateTextFile objFile, objFSO
        End If
    Next
End Sub

Public Sub CreateTextFile(ByVal objFile As Object, ByVal objFSO As Object)
    Dim objOut As Object, arrData As String, path As String
    path = objFile.path
    Set objFile = objFSO.OpenTextFile(objFile)
    Set objOut = objFSO.CreateTextFile(Left$(path, InStr(path, ".csv") - 1) & ".txt")

    arrData = objFile.ReadAll
    objOut.Write Replace(arrData, ",", vbTab)
    objFile.Close
    objOut.Close
End Sub