How to import a text file with Excel VBA
With Excel VBA you can export and import text files. This page shows how to import a semicolon delimited text file to a worksheet. Semicolon is used to separate cell content, and carriage return signals a new row.
I found most of the code on the Internet some years ago. Maybe it can be done in a smarter way, but it works fine for me.
The procedure "in control" of the operation is "Sub ImportDelimitedText()", while the function "ParseDelimitedString" and the procedure "UpdateCells" parse the text and insert it into the cells. See also how to write and export a text file with VBA.
Sub ImportDelimitedText()
Dim sDel As String * 1
Dim LineString As String
Dim sSourceFile As String
Dim sSepChar As String
Dim sTargetAddress As String
Dim rTargetCell As Range
Dim vTargetValues As Variant
Dim r As Long
Dim fLen As Long
Dim fn As Integer
On Error GoTo ErrorHandle
sSourceFile = "C:\filtest.txt"
sSepChar = ";"
sTargetAddress = "A1"
If Len(Dir(sSourceFile)) = 0 Then Exit Sub
If UCase(sSepChar) = "TAB" Or UCase(sSepChar) = "T" Then
sDel = Chr(9)
Else
sDel = Left(sSepChar, 1)
End If
Worksheets(1).Activate
Set rTargetCell = Range(sTargetAddress).Cells(1, 1)
rTargetCell.CurrentRegion.Clear
On Error GoTo BeforeExit
fn = FreeFile
Open sSourceFile For Input As #fn
On Error GoTo 0
fLen = LOF(fn)
r = 0
While Not EOF(fn)
Line Input #fn, LineString
vTargetValues = ParseDelimitedString(LineString, sSepChar)
UpdateCells rTargetCell.Offset(r, 0), vTargetValues
r = r + 1
Wend
Close #fn
BeforeExit:
Set rTargetCell = Nothing
Exit Sub
ErrorHandle:
MsgBox Err.Description & " Error in ImportDelimitedText."
Resume BeforeExit
End Sub
The function below parses ("reads") the text.
Function ParseDelimitedString(InputString As String, _
sDel As String) As Variant
Dim i As Integer, iCount As Integer
Dim sString As String, sChar As String * 1
Dim ResultArray() As Variant
On Error GoTo ErrorHandle
sString = ""
iCount = 0
For i = 1 To Len(InputString)
sChar = Mid$(InputString, i, 1)
If sChar = sDel Then
iCount = iCount + 1
ReDim Preserve ResultArray(1 To iCount)
ResultArray(iCount) = sString
sString = ""
Else
sString = sString & sChar
End If
Next i
iCount = iCount + 1
ReDim Preserve ResultArray(1 To iCount)
ResultArray(iCount) = sString
ParseDelimitedString = ResultArray
Exit Function
ErrorHandle:
MsgBox Err.Description & " Error in function ParseDelimitedString."
End Function
The following procedure writes the text to cells in the worksheet.
Sub UpdateCells(rTargetRange As Range, vTargetValues As Variant)
Dim r As Long, c As Integer
On Error GoTo ErrorHandle
If TypeName(ActiveSheet) <> "Worksheet" Then Exit Sub
r = 1
c = 1
On Error Resume Next
c = UBound(vTargetValues, 1)
r = UBound(vTargetValues, 2)
Range(rTargetRange.Cells(1, 1), rTargetRange.Cells(1, 1). _
Offset(r - 1, c - 1)).Formula = vTargetValues
Exit Sub
ErrorHandle:
MsgBox Err.Description & " Error in procedure UpdateCells."
End Sub
Related:
|