Mighty Badaboom
Mighty Badaboom

Reputation: 6155

Get full content from current word document

I have a MS-Word .docm document with a macro inside. In this macro I want to get the full content from the document as a byte array. The content should contain the full information of the document and when I save this content I should be able to open this file in Word again.

Im totally new to vba and don't have any idea where to start. I thought about saving the document in a temp folder to read this file to get the content but maybe there is a better way.

Upvotes: 1

Views: 545

Answers (1)

ignotus
ignotus

Reputation: 658

I suggest you to use

ThisDocument.SaveAs "c:\temp\mydoc.docm"

Then simply use that file for your further operation.

Or to print out your file as bytes:

Sub SaveAsByteArray()
    Dim thisFile  As String
    thisFile = ActiveDocument.FullName
    Dim targetFile As String
    targetFile = "C:\temp\doc.docm"
    Dim sourceFileNum As Integer
    Dim targetFileNum  As Integer

    Dim aByte As Byte

    sourceFileNum = FreeFile
    Open thisFile For Random Access Read As sourceFileNum Len = 1

    targetFileNum = FreeFile
    Open targetFile For Random Access Write As targetFileNum Len = 1

    Do While Not EOF(sourceFileNum)
        Get #sourceFileNum, , aByte
        Put #targetFileNum, , aByte
    Loop

    Close sourceFileNum
    Close targetFileNum
End Sub

But this sub adds an extra byte at the end, so Excel will open a dialog asking if you want to fix the contents. If you choose yes, then word is able to open the file.

Or put it into an array:

Sub SaveAsByteArray()
    Dim thisFile  As String
    thisFile = ActiveDocument.FullName
    Dim sourceFileNum As Integer

    Dim arr()
    Dim arr_n as long
    arr_n = 0

    Dim aByte As Byte

    sourceFileNum = FreeFile
    Open thisFile For Random Access Read As sourceFileNum Len = 1

    Do While Not EOF(sourceFileNum)
        Get #sourceFileNum, , aByte

        ReDim Preserve arr(0 to arr_n)
        arr(arr_n) = aByte
        arr_n=arr_n+1

    Loop

    Close sourceFileNum
End Sub

Upvotes: 2

Related Questions