Excel VBA: How to Open a Binary File

VBA & macros · Updated November 19, 2026

Yes. In Excel VBA on Windows, open a file with Open ... For Binary Access Read and use Get to read its bytes. Binary mode treats the file as byte data rather than text divided into lines, so it is useful when you need to inspect or process a file in its original byte form.

What binary mode means in VBA

A computer file is ultimately stored as bytes, but programs interpret those bytes according to a format. A text file might encode characters and use line breaks to separate records. A binary file may instead contain numbers, images, compressed data, or a format-specific sequence of fields. The word “binary” here describes how VBA accesses the file; it does not identify one particular file format.

VBA’s Open statement offers different modes for different tasks. For Input is intended for reading text, often a line at a time with Line Input #. For Output and For Append are text-file modes for creating or adding text. For Binary gives you byte-oriented access, while For Random is designed for fixed-length records. Choosing Binary does not automatically decode, validate, or understand the file. It only lets your code read or write the bytes.

Read a binary file into a byte array

This example prompts for a file, reads its full contents into a VBA byte array, and reports how many bytes it read. It deliberately does not attempt to interpret the file’s format. Save a copy of the workbook before running a macro: VBA changes cannot be reversed with Ctrl+Z.

Sub ReadBinaryFile()
    Dim filePath As Variant
    Dim fileNum As Integer
    Dim fileSize As Long
    Dim fileIsOpen As Boolean
    Dim bytes() As Byte
    Dim errorText As String

    filePath = Application.GetOpenFilename( _
        "All Files (*.*),*.*", , "Select a binary file")
    If VarType(filePath) = vbBoolean Then Exit Sub

    On Error GoTo ReadError

    fileNum = FreeFile
    Open CStr(filePath) For Binary Access Read As #fileNum
    fileIsOpen = True

    fileSize = LOF(fileNum)
    If fileSize > 0 Then
        ReDim bytes(0 To fileSize - 1) As Byte
        Get #fileNum, , bytes
    End If

    Close #fileNum
    fileIsOpen = False
    MsgBox CStr(fileSize) & " bytes read."
    Exit Sub

ReadError:
    errorText = Err.Description
    If fileIsOpen Then Close #fileNum
    MsgBox "Could not read the file: " & errorText, vbExclamation
End Sub

The empty-file check matters: an empty file has no valid last array index, so the code avoids trying to dimension an array from zero through minus one. GetOpenFilename returns False when the user cancels; checking for that prevents VBA from trying to open the Boolean value as a path. FreeFile supplies an available file number, and LOF returns the file’s length in bytes for this use.

In this code, Get #fileNum, , bytes reads the data into the already-sized dynamic byte array. The omitted record position tells VBA to read from the current file position, which is the beginning immediately after opening. The file is then closed before the message appears. The error handler also closes it if a read fails after opening.

How to adapt the example

The sample is a starting point, not a file-format parser. Once loaded, the array contains byte values from 0 through 255. For example, a byte value can be inspected with bytes(0), but its meaning depends on the format’s specification. The first bytes might be a signature, a length field, compressed content, or something else entirely. Do not assume that a byte corresponds to a printable character.

To do more than report the size, add logic after the Get statement. A parser might check that the file has a minimum expected length, verify a known signature, and then decode fields according to the format’s documented byte order and layout. For example, a two-byte integer could be stored with the low-order byte first or the high-order byte first. The array alone does not tell VBA which convention the format uses.

For small, well-defined files, reading the whole file at once is convenient. For large files, allocate a smaller buffer and process successive portions instead of holding every byte in memory. The exact chunk-reading design depends on the format and should account for incomplete final chunks. This whole-file example also relies on VBA’s Long-sized file-length handling and available memory, so it is not a suitable general-purpose method for files that may approach or exceed those limits.

Reading one byte or a section

If a task only needs a particular byte, reading the entire file is unnecessary. In Binary mode, VBA’s Get statement can use a record number to position a read. For binary files, that position is byte-based and begins at 1, not at the zero-based index commonly used by VBA arrays. After opening the file, a read at position 1 requests the first byte; a read at position 10 requests data beginning at the tenth byte.

Keep the distinction between file positions and array indexes clear. In the sample, the first array element is bytes(0), but the first byte position in the file is 1. Confusing these two conventions is a common source of off-by-one errors. Before requesting a range, check that the file is long enough; a position beyond the end cannot provide the expected data.

VBA also provides Seek for moving the current file position. This can be useful when a format has a header followed by data at a known location. A robust parser should validate the header and file length before seeking to a claimed offset, because malformed or unexpected input may specify a location outside the actual file.

Choose Binary, Input, or Random mode

Use the mode that matches the data and the operation rather than choosing based on the file extension alone. These are practical distinctions:

  • Binary: read or write bytes directly, including arbitrary content that is not line-oriented text.
  • Input: read text, commonly one line at a time; it is a natural choice for a plain-text list or log.
  • Output: create a text file for writing; opening an existing file this way can replace its contents.
  • Append: add text at the end of an existing text file or create it if it does not exist.
  • Random: access fixed-length records, where record structure and record length are part of the design.

If a file is actually text, opening it in Binary mode may be useful when exact bytes matter, but it makes character decoding your responsibility. Conversely, using a text mode for a proprietary binary format can distort the operation: line-reading logic is not an appropriate way to interpret arbitrary binary data.

Writing bytes and protecting the original

VBA can write byte data with Put after opening a file in a suitable write-capable mode. Be especially cautious with For Binary Access Write: writing starts at the current file position, and opening an existing file for writing does not itself make a safe backup. If your code overwrites the original, an error or incorrect offset can damage it. For experiments, write to a new output path and compare the result before replacing any source file.

Also distinguish between copying bytes and creating a valid file. A byte array written successfully may still be unusable if it lacks required headers, lengths, checksums, or encoding rules. When the target is a known format, follow that format’s documentation. When the target is an Excel workbook, use Excel’s workbook and worksheet object model to read or change cells rather than treating the workbook file as an unexplained stream of bytes.

Common errors and practical safeguards

Most problems come from an incorrect path, an unexpected file size, an unsuitable mode, or a misunderstanding of the format. The following checks help make file-handling code more reliable:

  • Confirm the selected path exists and that the account running Excel has permission to read it.
  • Use FreeFile instead of assuming a file number is unused.
  • Close the file after success and attempt cleanup after a run-time error.
  • Handle an empty file separately before sizing an array.
  • Validate minimum and maximum expected lengths before interpreting fields.
  • Do not show raw bytes as if they were readable text; arbitrary byte sequences may not be valid characters.
  • Test with a disposable copy and keep a backup, especially before adding write operations.

Macro settings are another practical consideration. Store code in a macro-enabled workbook such as an .xlsm file, and only enable macros from sources you trust. A macro that opens a file can still fail because of permissions, a locked file, an invalid path, or an unexpected format; the error handler makes the failure more visible, but it does not make untrusted input safe.

Windows, Mac, and Excel for the web

The example is written for Excel for Microsoft 365 on Windows. In the Windows desktop app, Alt+F11 opens the Visual Basic Editor; depending on the keyboard, you may need to press Fn as well. On Excel for Mac, Option+F11 commonly opens the editor, with Fn sometimes required by the keyboard’s function-key setting. Mac file paths differ from Windows paths, so avoid hard-coding a Windows-style path if a workbook must run on both platforms. The file picker in the example helps avoid that particular issue, though platform behavior and permissions can differ.

Excel for the web does not run VBA macros. Use the Windows or Mac desktop application to execute this code. If you need browser-based automation, investigate Office Scripts or another supported tool, but those are not VBA and do not provide a drop-in replacement for every file-system operation.

Frequently Asked Questions

Can Excel VBA open any binary file?
VBA can open many files for byte-level reading if the operating system permits access, but opening is not the same as understanding. Your code needs the format specification to interpret the bytes correctly, and some files may be too large or otherwise unsuitable for the whole-file example.

Can I use VBA to read a binary file into a worksheet?
You can place selected byte values into worksheet cells, but a worksheet is usually not a sensible destination for an entire file. Worksheets have row and column limits, and bytes are not automatically meaningful cell values. Parse the format first and write only the useful fields.

Is an XLSX file a binary file?
An XLSX workbook is a packaged format containing XML parts and other resources, rather than a simple text file or one flat stream of cell data. Reading its raw bytes with Binary mode does not provide a convenient way to retrieve workbook values. Open it with Excel and use VBA’s workbook object model.

Why does my binary read return unexpected characters?
A byte is not necessarily a character. If the content is text stored in a particular encoding, it must be decoded using that encoding; if it is genuinely binary, displaying the bytes as text can produce meaningless symbols. Check the file format before converting bytes to strings.

Can I run this macro in Excel for the web?
No. Excel for the web can open and edit many macro-enabled workbooks, but it does not execute VBA. Run the macro in desktop Excel for Windows or Mac, subject to that platform’s file access and macro settings.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.