-1

Hello, as the title states I need a Visual Basic code that loops through a folder and search for ,csv and then converts CSV files to text files, I found this code but it only works for a single file :

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
Asayel
  • 3
  • 4
  • Possible duplicate of [Loop through files in a folder using VBA?](https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba) – urdearboy Sep 01 '18 at 17:50
  • You can put the conversion into a function and then use the file looping functionality of fso with a file mask for csv included. You can use .GetExtensionName for that. https://stackoverflow.com/questions/38354947/using-vba-filesystemobject-specific-file-file-extension – QHarr Sep 01 '18 at 18:12

1 Answers1

0

This is a rough idea of what converting it to using an additional sub would look like in relation to your code. Pretty sure there are better ways but this is written to resemble your code. For example, an improvement would be to implement as a class that had a convert method rathering than passing references around.

You would also, presumably, want to implement a clean up routine to delete the csvs?

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
QHarr
  • 83,427
  • 12
  • 54
  • 101