VBA to Delete data in TXT file

In VBA, you cannot directly delete data from a specific location within a text file. However, you can overwrite the contents of the text file to remove the desired data. Here’s an example of VBA code that demonstrates how to overwrite the contents of a text file to delete data:

Sub DeleteDataInTXT()
    Dim filePath As String
    filePath = "C:\Path\to\your\File.txt" ' Replace with the path to your text file
    
    ' Specify the data to be deleted
    Dim deleteText As String
    deleteText = "Data to be deleted" ' Replace with the data you want to delete
    
    ' Read the contents of the text file
    Dim fileContent As String
    Open filePath For Input As #1
    fileContent = Input$(LOF(1), #1)
    Close #1
    
    ' Delete the data from the file content
    fileContent = Replace(fileContent, deleteText, "")
    
    ' Write the updated content back to the text file
    Open filePath For Output As #1
    Print #1, fileContent
    Close #1
End Sub

In this code, you need to modify the filePath variable to specify the path and filename of your text file. Replace "C:\Path\to\your\File.txt" with the actual path and filename.

Additionally, modify the deleteText variable to specify the data you want to delete from the text file.

When you run this code, it reads the contents of the text file into the fileContent variable, replaces the specified data (deleteText) with an empty string to effectively delete it, and then writes the updated content back to the text file, overwriting the previous contents.

Note: This code will replace all occurrences of the deleteText within the text file. If you need to perform more specific deletion logic, you may need to use advanced techniques such as regular expressions or parsing the file line by line.

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