PDA

View Full Version : Modify code to extract data from a text file



swaggerbox
05-16-2011, 02:10 AM
A code below by Mark (see http://www.vbaexpress.com/forum/showthread.php?t=31784) extracts data from sample.txt containing the following information: <date Year="2008" Month="09" Day="18"/> into an excel file, formatting the data into a single cell, e.g. 20080918

I would like to modify this code so that it extracts the whole part ("<date Year="2008" Month="09" Day="18"/>") instead of joining them.

Any ideas



Option Explicit

Sub exa()
Dim _
strLine As String, _
strLineOut As String, _
i As Long

With CreateObject("Scripting.FileSystemObject").OpenTextFile(ThisWorkbook.Path & "\sample.txt")
strLine = .ReadAll
.Close
End With

With CreateObject("VBScript.RegExp")
.Global = False
.MultiLine = True
.Pattern = "(<date)(.+)(/>)"

If .Test(strLine) Then
strLine = .Execute(strLine)(0)
For i = 1 To Len(strLine)
If IsNumeric(Mid(strLine, i, 1)) Then
strLineOut = strLineOut & Mid(strLine, i, 1)
End If
Next
Range("A1").Value = CLng(strLineOut)
End If
End With
End Sub