I'm having trouble working out why a bit of code that I found months and months ago (don't know originating website) is doing such a weird thing when trying to save the file...
In the main part of the code that is constantly looping it has the following:
Main Snippit
path = "C:/"
filename = "file.csv"
If Dir(path) = "" Then
FullPath = Environ("USERPROFILE") & "\Desktop\" & filename
Else
FullPath = path & filename
If Dir(FullPath) <> "" Then
isCsvOpen = IsFileOpen(FullPath)
If Not isCsvOpen Then Kill (FullPath)
End If
End If
If Not isCsvOpen Then outputtext delimiteddata, FullPath
It has the following two functions elsewhere in the code:
outputtext()
Function outputtext(text As String, path As String)
Dim MyFile As String, fnum As String
MyFile = path
fnum = FreeFile() ' Get a free file number.
Open MyFile For Output As fnum 'open file for output
Print #fnum, text ' Print when you want the string without quotation marks
Close #fnum
End Function
IsFileOpen()
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
Case Else
Error errnum
End Select
End Function
What is the purpose of using IsFileOpen()
and outputtext()
, surely just saving with overwrite would be sufficient?
To me it looks like it's checking if the file is open, locking it open, then killing the file (unlocking it) and then saving...
Any explination would be much appreciated