View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
RB Smissaert RB Smissaert is offline
external usenet poster
 
Posts: 2,452
Default How to put lines with certain text (from a file) in an array

Function OpenTextFileToString(strFile As String) As String

Dim hFile As Long

On Error GoTo ERROROUT

hFile = FreeFile
Open strFile For Binary As #hFile
OpenTextFileToString = Space(LOF(hFile))
Get hFile, , OpenTextFileToString
Close #hFile

Exit Function
ERROROUT:

If hFile 0 Then
Close #hFile
End If

End Function


Sub Test()

Dim i As Long
Dim n As Long
Dim str As String
Dim arr1
Dim arr2() As String

str = OpenTextFileToString("C:\testfile.txt")

arr1 = Split(str, vbCrLf)

ReDim arr2(0 To UBound(arr1)) As String

For i = 0 To UBound(arr1)
If InStr(1, arr1(i), "layer_", vbBinaryCompare) 0 Then
arr2(n) = arr1(i)
n = n + 1
End If
Next i

ReDim Preserve arr2(0 To n - 1) As String

'to check we got it right
For i = 0 To UBound(arr2)
MsgBox arr2(i), , i
Next i

End Sub


RBS


"Varun" wrote in message
...
Guys,

I'd like to open and parse a file such that when I parse, only lines with
certain text in them get included into my array. How can I accomplish
this?
For example, let say that file contents are as follows:

text in line 1
text in line 2
layer_1
layer_2
layer_3

I'd like to save the lines with layer_1, layer_2, and layer_3 in my array
named line.

Here's what I have so far - what should I do next?

Sub geomsasciiparse()

Dim Buf() As String
Dim logical_layer As Variant
Dim line() As String

Dim objFSO As Object
Dim objGeomsAsciiFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objGeomsAsciiFile = objFSO.OpenTextFile(MentDesContPath &
"\geoms_ascii")
strBuffer = objGeomsAsciiFile.Readline

Do While Not objGeomsAsciiFile.AtEndOfStream

If InStr(strBuffer, "layer") = 1 Then




End If

Thanks for help.