VBA to Update data in TXT file

In VBA, you cannot directly update specific data in a text file. However, you can read the contents of the text file, modify the desired data in memory, and then overwrite the entire file with the updated content. Here’s an example of VBA code that demonstrates this process:

Sub UpdateDataInTXT()
    Dim filePath As String
    Dim fileContents As String
    Dim newData As String
    Dim fileNumber As Integer

    ' Specify the path to the text file
    filePath = "C:\Path\to\your\File.txt" ' Replace with the path to your text file

    ' Specify the new data to be updated
    newData = "New Data" ' Replace with the new data you want to update

    ' Read the contents of the text file
    fileNumber = FreeFile
    Open filePath For Input As fileNumber
    fileContents = Input$(LOF(fileNumber), fileNumber)
    Close fileNumber

    ' Modify the desired data
    ' Assuming you want to replace "Old Data" with "New Data"
    fileContents = Replace(fileContents, "Old Data", newData)

    ' Write the updated contents back to the text file
    Open filePath For Output As fileNumber
    Print #fileNumber, fileContents
    Close fileNumber
End Sub

In this code, you need to modify the filePath variable to specify the path to your text file. Additionally, replace "Old Data" with the actual existing data you want to update and "New Data" with the new data you want to replace it with.

When you run this code, it reads the entire content of the text file into memory, modifies the desired data using the Replace function, and then overwrites the entire file with the updated content.

Note: The code assumes that the text file is in a readable and writable location. Make sure you have the necessary permissions to read from and write to the specified file.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech