kevenson,
Are all of the text files in the same folder? Are they tab delimited or comma delimited, etc? Do you want to save the sheets as excel files or as text files?
Assuming yes, tab delimited, and excel files:
Sub tgr()
'Change to the correct folder paths, be sure to include the ending \
Const strFldrPath As String = "C:\Test\"
Const strSavePath As String = "C:\Test\Converted Files\"
'Declare variables
Dim lCalc As XlCalculation
Dim FSO As Object
Dim oFile As Object
Dim findArray() As Variant
Dim replArray() As Variant
Dim arrText() As String
Dim strName As String
Dim i As Long
'Turn off various settings to enahnce performance
With Application
lCalc = .Calculation
.Calculation = xlCalculationManual
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
End With
'Assume code will fail so that settings will always get turned back on
On Error GoTo CleanExit
Set FSO = CreateObject("Scripting.FileSystemObject")
findArray = Array("av1121", "bv1121 ", "ac1121")
replArray = Array("va1121", "vb1121 ", "gq1121")
'Check each file in the Folder Path
For Each oFile In FSO.GetFolder(strFldrPath).Files
'Check if the file is a txt file
If LCase(FSO.GetExtensionName(oFile.Path)) = "txt" Then
'Found to be a text file, get its contents
arrText = Split(FSO.OpenTextFile(oFile.Path).ReadAll, vbNewLine)
'Create a new sheet for the contents and perform various operations
With Sheets.Add
'Guarantee valid sheet name
strName = Replace(oFile.Name, ".txt", vbNullString, Compare:=vbTextCompare)
For i = 1 To 7
strName = Replace(strName, Mid(":\/?*[]", i, 1), vbNullString)
Next i
strName = Left(WorksheetFunction.Trim(strName), 31)
'Name the sheet
.Name = strName
'Populate the sheet with the text file's data
.Range("A1").Resize(UBound(arrText) - LBound(arrText) + 1).Value = Application.Transpose(arrText)
.UsedRange.TextToColumns .UsedRange, xlDelimited, xlTextQualifierDoubleQuote, True, Tab:=True
'Perform find and replace
For i = LBound(findArray) To UBound(findArray)
.UsedRange.Replace findArray(i), replArray(i)
Next i
'Make the sheet its own workbook then save and close the new workbook
.Move
ActiveWorkbook.SaveAs strSavePath & strName & ".xls", xlExcel8
ActiveWorkbook.Close False
End With
End If
Next oFile
CleanExit:
'Turn application settings back on
With Application
.Calculation = lCalc
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
End With
'Display error message, if any
If Err.Number <> 0 Then
MsgBox Err.Description, , "Error: " & Err.Number
Err.Clear
End If
'Cleanup
Set FSO = Nothing
Set oFile = Nothing
Erase arrText
Erase findArray
Erase replArray
End Sub
Bookmarks