I am a novice and adapted some code found in the forum to read a text file, find specific data in that file, and write it to an Excel sheet.
It works properly to find the data, but the macro stops unexpectedly, immediately after changing a cell in the active sheet.
I know that the code successfully identifies the data I want, because if I Debug.Print the result to the Immediate window instead of writing to the active sheet, all the results are there.
But any version of code I write that changes any cell in the active sheet causes the macro to immediately stop.
What am I doing wrong?
Grateful for any help I can get!
It works properly to find the data, but the macro stops unexpectedly, immediately after changing a cell in the active sheet.
I know that the code successfully identifies the data I want, because if I Debug.Print the result to the Immediate window instead of writing to the active sheet, all the results are there.
But any version of code I write that changes any cell in the active sheet causes the macro to immediately stop.
What am I doing wrong?
Grateful for any help I can get!
VBA Code:
Private Sub CommandButton1_Click()
Const FindText = "Total sludge adsorption: "
Dim fData As String, fPath As String, TextLine As String, FileNum As Integer, Rw As Integer
fPath = GetPath
If fPath = "" Then GoTo TheEnd
Rw = 1
'Cells(Rw, "A").Resize(, 1) = Array("SludgePercent") 'Labels the column before adding data - if this line of code is enabled, the macro stops here and only the column name is written
FileNum = FreeFile()
Open fPath For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, TextLine
TextLine = Trim(TextLine)
If Left(TextLine, 28) = FindText Then 'Looks for the data label preceding the data I want
Debug.Print Replace(Replace(TextLine, FindText, ""), " percent", "") 'This prints all the data successfully to the Immediate window
Rw = Rw + 1
'Cells(Rw, 1) = Replace(Replace(fData, FindText, ""), " percent", "") 'This should write the results to the active sheet - If this line of code is enabled, the macro stops here and only one result is written
End If
Wend
Close #FileNum
Exit Sub
TheEnd:
MsgBox "file not selected", , ""
End Sub
Private Function GetPath() As String
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Add "Text", "*.txt"
.Show
If .SelectedItems.count = 1 Then GetPath = .SelectedItems.Item(1)
End With
End Function