PDA

View Full Version : Solved: Convert delimited string into an array



mdmackillop
09-21-2004, 05:10 AM
I want to split lines of text delimited by "|" to form a 4 dimensional array from the contents, for use in a UserForm. Is there a RegExp or similar to do this neatly? :confused: The delimiter can be changed if this would make life simpler. The lines will be read from a text file (attached)
MD


001|P:\1028 Crieff Golf Club DDA\14.04.04\|140404-001.jpg|Stair Landing
002|P:\1028 Crieff Golf Club DDA\14.04.04\|140404-002.jpg|Toilet Entrance
003|P:\1028 Crieff Golf Club DDA\14.04.04\|140404-003.jpg|No wheelchair access at bars

Tommy
09-21-2004, 06:19 AM
Hi MD,

Try

Dim mArr() As String
mArr = Split("001|P:\1028 Crieff Golf Club DDA\14.04.04\|140404-001.jpg|Stair Landing", "|")

This will return a 0 based array

Later
Tommy

mdmackillop
09-21-2004, 02:08 PM
Thanks Tommy,
I can manipulate that to suit my needs.
MD

Tommy
09-21-2004, 02:25 PM
You aren't trying to copy this file into an array(0 to 15, 0 to 3) are you?

mdmackillop
09-21-2004, 02:29 PM
Yes, That's the result I'm after.
I'm using the following, but I'm sure there must be a more direct way

Do While ts.AtEndOfStream <> True
i = i + 1
myArr = Split(ts.readline, "|")
For Each m In myArr
j = j + 1
MyList(i, j) = m
Next
j = 0
Loop

Tommy
09-21-2004, 02:42 PM
The only way I know is CopyMemory (API) call. Massive speed increase, but will cause problems if not done properly. You can copy either the actual data or just the memory address. It works a lot easier with doubles, integers, long. The problem with strings is VB sets a string with a vbnullstring(0 bytes), a long is 0 (1 byte) 453 is 1 byte. SO to get it to work you have to dump spaces into the string to make it have something to copy to.

mdmackillop
09-21-2004, 02:46 PM
Sounds complicated! I'll only ever have 50 - 100 lines, so I'll go with the Split for now.
Thanks for the pointer.

Bilby
09-21-2004, 09:47 PM
How about this;


Public Sub OpenTextFileTest()
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Dim fs, f, s
Dim i, j, m, result
Dim myArr(0 To 14, 0 To 3) As String
i = 0: j = 0

'' Open TextFile and read one line at a time
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.OpenTextFile("C:\TEMP\DDA Report.txt", ForReading)
Do While f.AtEndOfLine <> True
s = f.readline
'' Split a line into single dimensioned array
result = Split(s, "|")
'' Dump Single array elements into multi-dimensioned
For j = 0 To 3
myArr(i, j) = result(j)
Next j
i = i + 1
Loop
f.Close

'' Testing section - dump the lot to debug
i = 0: j = 0
For i = LBound(myArr) To UBound(myArr)
For j = 0 To 3
Debug.Print i & "/" & j & vbTab & myArr(i, j)
Next j
Next i
End Sub

mdmackillop
09-21-2004, 11:52 PM
Hi Bilby,
A little bit neater than mine.
Thanks
MD