How can I GZip compress a file from Excel VBA using code in an .xla file only?

前端 未结 5 1309
情深已故
情深已故 2021-01-06 08:32

I need to be able to GZip compress a file in an Excel VBA function. Specifically I need to be able to use the \'deflate\' algorithm.

Is there a way to do this withou

5条回答
  •  没有蜡笔的小新
    2021-01-06 09:05

    If you want to implement the algorithm in VBA, you would need to (in VBA) save the spreadsheet and then use VB's I/O functions to open the file, deflate it, and save it again. For all intents and purposes it's identical to writing an ordinary VB application that works on a file. You might need to put the VBA macro in a separate workbook to avoid "file in use" types of errors, but if you reopen the file as read-only and save it with a different filename you should be OK keeping everything in one workbook.

    But I'm almost certain that shelling out to gzip from within the VBA would be functionally identical and infinitely easier.

    EDIT: Some code. It didn't fail when I ran it, so it's OK to keep everything in the same workbook.

    Sub main()
        ActiveWorkbook.Save
        Open "macrotest.xls" For Binary Access Read As #1
        Open "newfile.zip" For Binary Access Write As #2
            'do your stuff here
        Close #2
        Close #1
    End Sub
    

提交回复
热议问题