How to use Put statement in VBA?

In VBA (Visual Basic for Applications), the Put statement is used to write data to a file opened in Binary mode or Random mode. It’s commonly used for writing binary data or records to a file.

Here’s a guide on how to use the Put statement:

Using Put in Binary Mode

Open a File in Binary Mode

You first need to open a file in Binary mode using the Open statement.

VBA
Open "filename" For Binary As #fileNumber

Write Data Using Put

The Put statement is then used to write data to the file. You specify the file number and the position at which to start writing. If you omit the position, the writing starts at the current position.

VBA
Put #fileNumber, , dataVariable
  • fileNumber is the file number used in the Open statement.
  • dataVariable is the variable containing data you want to write.

Example

Writing a string to a binary file.

VBA
Dim myString As String
myString = "Hello, World!"

Open "C:\example.bin" For Binary As #1
Put #1, , myString
Close #1

Using Put in Random Mode

Define a User-Defined Type (UDT)

When using Random mode, you usually define a UDT to structure the data in the file.

VBA
Type Employee
    ID As Integer
    Name As String * 50
    Salary As Double
End Type

Open a File in Random Mode

Open the file in Random mode, specifying the record length.

VBA
Open "filename" For Random As #fileNumber Len = Len(RecordVariable)

Write a Record Using Put

Use the Put statement to write the entire record to the file.

VBA
Open "filename" For Random As #fileNumber Len = Len(RecordVariable)

recordNumber is the record number where the data should be written. If omitted, the next record is written.

Example

Writing a record to a file.

VBA
Dim emp As Employee
emp.ID = 1
emp.Name = "John Doe"
emp.Salary = 50000

Open "C:\employees.dat" For Random As #1 Len = Len(emp)
Put #1, 1, emp
Close #1

Important Points

  • Binary Mode: In Binary mode, you can write any type of data, but you need to manage the data structure yourself.
  • Random Mode: In Random mode, the Put statement is typically used with user-defined types. This mode is suitable for fixed-length records.
  • File Number: Always ensure you’re using the correct file number that corresponds to your Open statement.
  • Close Files: Always close the files when you’re done to release the resources.

Using Put is a way to handle low-level file operations in VBA, and it’s especially useful for binary file manipulation or when dealing with structured data files.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *