Bruno Tassara
Bruno Tassara

Reputation: 1

VBA - Excel Unable to dettect file size increase

This one is driving me crazy. Any help is welcome.

I have a numeric simulaiton that constantly writes to a text file. The file size increases constantly. I need to report file size and check if it's still increasing or if it has ceased increasing.

VBA can't seem to detect the file's increased size, it keeps registering the same size. But, if I have windows explorer oppened on the file folder and press F5, the size increases in VBA.

I need to know if it is supposed to work this way because how windows indexes files or if I'm doing something wrong.

I have used filelen(), filesystemobject.filezise(), datelastmodified(),datelastacessed() and nothing...

I've already found a workarround: If I copy the file in question to a temp file and then read the temp file size, I can detect the change in size. But this is an ugly solution. I would very much like to just check the file size and get the correct result.

Sorry if it isn't very clear. I will be happy to clarify further, should it be necessary.

Here is the code I've been using, but to test it you would have to mimic the file writing situation, like in a video encoding for example, because if you do it with a text file edited in notepad, the act of saving it also updates the information to vba.

Public fileSizeLastStep as long

Public Sub sizeWatch()
    dim fso as new fileSystemObject
    dim fileToMeasure as File
    dim fileSizeNow as long

    Set fileToMeasure = fso.GetFile("C:\filename.txt")
    fileSizeNow = fileToMeasure.Size

    If fileSizeNow <> fileSizeLastStep Then
        fileSizeLastStep = fileSizeNow
        Set fso = Nothing
        Call Application.OnTime(Now + TimeValue("00:02:00"), "sizeWatch")
    Else
        MsgBox "Simulation Finished!"
        'calls whathever function that starts next simulation
    End If
End Sub

Thank you for your time.

Upvotes: 0

Views: 436

Answers (1)

Eliot
Eliot

Reputation: 91

Perhaps it's an issue with this: https://blogs.msdn.microsoft.com/oldnewthing/20111226-00/?p=8813

Quote from the article:

If you really need the actual file size right now, you can do what the first customer did and call Get­File­Size. That function operates on the actual file and not on the directory entry, so it gets the real information and not the shadow copy. Mind you, if the file is being continuously written-to, then the value you get is already wrong the moment you receive it.

So try using GetFileSize instead.

 Declare Function GetFileSize Lib "kernel32.dll" (ByVal hFile As Long, lpFileSizeHigh As Long) As Long 

Upvotes: 1

Related Questions