View Single Post
  #9   Report Post  
Posted to microsoft.public.excel.programming
GS[_6_] GS[_6_] is offline
external usenet poster
 
Posts: 1,182
Default Why the heck doesn't this work?

On Tuesday, June 4, 2019 at 1:54:31 AM UTC-7, GS wrote:

'Get the file contents and parse each line
vText = Split(ReadTextFile(sFile), vbCrLf)


Garry,

What if the above line crashes for any reason? Like if the
file referenced by "sFile" does not exist? If there's an error
of any kind while reading the file, I'd like vText to contain
the empty string "". How do I do that?

Thanks!


You could dump the file into a string variable before splitting the lines into
vText...

Dim sData$
sData = ReadTextFile(sFile)
If Len(sData) 0 Then vText = Split(sData, vbCrLf)

OR
You could check if the file exists before reading it:

If FileExists(sFile) Then
sData = ReadTextFile(sFile)
If Len(sData) 0 Then
vText = Split(sData, vbCrLf)
Else
'do something else...
End If 'Len(sData)
Else
'do something else...
End If 'FileExists


Public Function FileExists(Filename$) As Boolean
Dim nAttr As Long
' Grab this files attributes, and make sure it isn't a folder.
' This test includes cases where file doesn't exist at all.
nAttr = GetFileAttributes(Filename)
If (nAttr And vbDirectory) < vbDirectory Then
FileExists = True
ElseIf Err.LastDllError = ERROR_SHARING_VIOLATION Then
FileExists = True
End If
End Function

--
Garry

Free usenet access at http://www.eternal-september.org
Classic VB Users Regroup!
comp.lang.basic.visual.misc
microsoft.public.vb.general.discussion