I'm trying to import all csv files in a folder into new worksheets in an Excel file while retaining the text format.
I pieced together some code through some research and have it nearly working the way I need, but when I run the macro, all of the columns are set to General.
Any insight into this is greatly appreciated.
Sub ImportCSV()
Application.ScreenUpdating = False
Const conSpath As String = "C:\MyPath\"
Dim sMasterFile As String
Dim sSheetName As String
Dim sFile As String
Dim iNextSheet As Integer
ChDir conSpath
sMasterFile = ActiveWorkbook.Name
iNextSheet = Sheets.Count
sFile = Dir(conSpath & "*.csv", vbNormal)
While sFile <> ""
Workbooks.OpenText Filename:=sFile, _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), _
Array(2, 2), Array(3, 2), Array(4, 2), Array(5, 2)), TrailingMinusNumbers:=True
sSheetName = ActiveSheet.Name
Sheets(sSheetName).Copy After:=Workbooks(sMasterFile).Sheets(iNextSheet)
Workbooks(sFile).Close SaveChanges:=False
iNextSheet = iNextSheet + 1
sFile = Dir
Wend
Application.ScreenUpdating = True
End Sub
Edit: I was able to change the columns to text, but I am still losing my leading zeros.
Sub ImportCSV()
Application.ScreenUpdating = False
Const conSpath As String = "C:\MyPath\"
Dim sMasterFile As String
Dim sSheetName As String
Dim sFile As String
Dim iNextSheet As Integer
ChDir conSpath
sMasterFile = ActiveWorkbook.Name
iNextSheet = Sheets.count
sFile = Dir(conSpath & "*.csv", vbNormal)
While sFile <> ""
Workbooks.OpenText FileName:=sFile, _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, _
FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2), _
Array(5, 2)), TrailingMinusNumbers:=True
sSheetName = ActiveSheet.Name: Sheets(sSheetName).Cells.NumberFormat = "@"
Sheets(sSheetName).Copy After:=Workbooks(sMasterFile).Sheets(iNextSheet)
Workbooks(sFile).Close True
iNextSheet = iNextSheet + 1
sFile = Dir
Wend
Application.ScreenUpdating = True
End Sub