I'm getting a runtime error 75 file/path access error due to the script "forgetting" the filepath name stored in ReadTextFile
The file being read looks something like this:
%
O1234( 1234567.01 1ST.NCF )
stuff
( TOOL 25: 38.1 FACE ENDMILL )
( 1 1/2" FACE MILL )
stuff
( TOOL 22: 101.6 FACE ENDMILL )
( 4" FACE MILL )
stuff
M30
%
Sheet1 looks something like this:
Vert 4
C:\Data\My Code\1234567\Place\1234567.07 1st.NCF
C:\Data\My Code\5789975\Folder\5789975.12 2nd.NCF
C:\Data\My Code\32478\Subfoler 5\32478.35 1st.NCF
And the script is as follows:
Sub ExtractDataFromFiles()
Dim wb As Workbook
Dim wsQuery As Worksheet
Dim wsData As Worksheet
Dim LastRow As Long
Dim FileCell As Range
Dim FileText As String
Dim TextLine As Variant
Dim ToolData As String
Dim Extract As Boolean
' Set references to worksheets
Set wb = ThisWorkbook
Set wsQuery = wb.Sheets("Sheet1")
Set wsData = wb.Sheets("Sheet2")
' Clear the data on the destination sheet
wsData.Cells.Clear
' Loop through each file path in column D of the Query sheet
LastRow = wsQuery.Cells(wsQuery.Rows.Count, "D").End(xlUp).Row
For Each FileCell In wsQuery.Range("D2:D" & LastRow)
FileText = ReadTextFile(FileCell.Value)
' Check if the file could not be opened
If FileText = "File Not Found" Then
' Handle the error as needed (e.g., display a message)
MsgBox "File not found: " & FileCell.Value
Exit Sub ' Skip processing this file and move to the next one
End If
' Reset variables for each file
ToolData = ""
Extract = False
' Split the file text into an array of lines
Dim Lines() As String
Lines = Split(FileText, vbNewLine)
' Loop through each line in the array
For Each TextLine In Lines
If InStr(1, TextLine, "%", vbTextCompare) > 0 Then
' Extract the line after the first percent sign
Extract = True
ElseIf Extract Then
' Extract the line that follows the previously extracted line
ToolData = ToolData & TextLine & vbNewLine
Extract = False
ElseIf InStr(1, TextLine, "( TOOL ", vbTextCompare) > 0 Then
' Extract lines that start with "( TOOL "
ToolData = ToolData & TextLine & vbNewLine
Extract = True
End If
Next TextLine
' Write the extracted data to the destination sheet
wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = ToolData
Next FileCell
End Sub
Function ReadTextFile(ByVal FilePath As String) As String
' This function reads a text file and returns its contents as a string
Dim FileContent As String
Dim FileNum As Integer
FileNum = FreeFile
Open FilePath For Input As FileNum
FileContent = Input$(LOF(FileNum), FileNum)
Close FileNum
ReadTextFile = FileContent
End Function
Bookmarks