I'm writing an Excel VBA program to take measurements of equipment and update values at various readings. Here is a brief sample of what my file looks like:
[11904]
400: 0.4
500: 0.3
600: 3.3
[11905]
400: 1.0
500: 2.0
600: 3.0
The number in the brackets is the S/N of the equipment being used, the big number is the measurement and the number after the colon is the equipment's offset value. What I want to do is write something that will locate the S/N, locate the measurement value, then overwrite the offset value. The .ini file has A LOT of S/Ns that all take the same measurement but have different offsets. Here is some demo code I've tried from Spreadsheet Guru:
Private Sub CommandButton1_Click()
'PURPOSE: Modify Contents of a text file using Find/Replace
'SOURCE: www.TheSpreadsheetGuru.com
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
'File Path of Text File
FilePath = "C:\Temp\test.ini"
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
'Store file content inside a variable
FileContent = Input(LOF(TextFile), TextFile)
'Clost Text File
Close TextFile
'Find/Replace
FileContent = Replace(FileContent, "[HEADER TEST]", "[HEADER TEST]")
FileContent = Replace(FileContent, "Inserting new line", "Replacing line")
FileContent = Replace(FileContent, "Blah blah blah", "replaced this line too!")
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Write State
Open FilePath For Output As TextFile
'Write New Text data to file
Print #TextFile, FileContent
'Clost Text File
Close TextFile
End Sub
The code works, but it updates anything that says "Inserting new line" and "blah blah blah." I was hoping it would only replace one occurrence once I had it find the "[HEADER TEST]."
My issue is two-fold:
How do I only change, say, measurement "400" for just one S/N in the file?
Also, once I locate text I want to change, how do I only write the offset value instead of the entire string?
If I'm able to successfully locate a line and only edit one line, I can just replace the entire string if need be. I cannot change the .ini's format, as we use a program that reads it.