extracting searched term and previous line vba











up vote
-1
down vote

favorite












Is there any way I can do to extract the previous sentence or the line above the searched word?



I am trying to extract it from multiple text files. so far I only managed to get the searched term to pop up, but not the text above it.



I am kinda new in VBA so I did pick a few things from others who have codes that solved my problems.



Public errors As Integer
Public X As Variant
Public Y As Variant
Public Sub testing()
Dim fldr As FileDialog
Dim sItem As String

Dim z As Variant
Dim ID As String
Dim reminder As String
Dim confirmation As String
z = Now()
start:

If UserForm1.CommandButton1 = True Then
Set X = CommandButton1.Name
End If



Y = Application.InputBox("Please enter your Employee ID", "For Verification Purposes", Type:=1)
Select Case Y
Case Y = ""
Exit Sub
End Select
ID = MsgBox("Is your Employee ID, " & (Y) & ", correct?", vbYesNo, "Confirm?")
Select Case ID
Case vbYes
GoTo foldersetting
Case vbNo
GoTo start
End Select




foldersetting:
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder for " & (X)
.AllowMultiSelect = True
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With

NextCode:
getfolder = sItem
Set fldr = Nothing

If getfolder = "" Then Exit Sub

Dim fso As Object
Dim fld As Object
Dim strSearch, strsearch1 As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

' On Error GoTo ErrHandler
Application.ScreenUpdating = False



'Change as desired
strPath = sItem '//////////////// <--- Change directory here \\\\\\\\\\\\
strSearch = "Result: FAIL" '///////////////// <--- Change term to search for here \\\\\\\\\\\
Set wOut = Worksheets.Add

Application.StatusBar = True

Application.StatusBar = "Please Wait..."

lRow = 1
With wOut
.Cells(lRow, 1) = "Type: " & (X)
.Cells(lRow, 2) = "Employee ID: " & (Y)
.Cells(lRow, 3) = "Date & Time of Extract: " & (z)
.Cells(lRow, 4) = "" 'Reserved for future use.
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.getfolder(strPath)




strFile = Dir(strPath & "*.txt") '<-- Currently searching all Log files. Change extension here
Do While strFile <> ""
Set wbk = Workbooks.Open _
(Filename:=strPath & "" & strFile, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)


For Each wks In wbk.Worksheets
Set rFound = wks.UsedRange.Find(strSearch)
If Not rFound Is Nothing Then
strFirstAddress = rFound.Address
End If
Do
If rFound Is Nothing Then
Exit Do
Else
lRow = lRow + 1
.Cells(lRow, 1) = rFound.Value

.Cells(lRow, 2) = wbk.Name


End If
Set rFound = wks.Cells.FindNext(after:=rFound)

Loop While strFirstAddress <> rFound.Address
Next


wbk.Close (False)
strFile = Dir


Loop
.Columns("A:D").EntireColumn.AutoFit


End With
errors = (ActiveSheet.UsedRange.Rows.Count - 1)


If (ActiveSheet.UsedRange.Rows.Count - 1) > 0 Then
MsgBox "There are " & (ActiveSheet.UsedRange.Rows.Count - 1) & " Failures Found!", vbCritical, "Warning"
ElseIf (ActiveSheet.UsedRange.Rows.Count - 1) = 0 Then
MsgBox "No errors found.", vbInformation, "No Errors"
Dim sh As Worksheet
Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
End If

Dim lastrow As Long
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 2

ActiveSheet.Cells(lastrow, "A").Value = "Number of Failures: " &
(ActiveSheet.UsedRange.Rows.Count - 1)
On Error GoTo calling
Dim rngData As Range
Dim strData As String
Dim strTempFile As String

' copy some range values
Set rngData = wOut.Range("A:D")
rngData.Copy

' get the clipboard data
' magic code for is for early binding to MSForms.DataObject
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.GetFromClipboard
strData = .GetText
End With

' write to temp file
strTempFile = "D:temp.txt"
With CreateObject("Scripting.FileSystemObject")
' true to overwrite existing temp file
.CreateTextFile(strTempFile, True).Write strData
End With

' open notepad with tempfile
Shell "cmd /c ""notepad.exe """ & strTempFile & """", vbHide
calling:
Call log

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True

Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
Application.StatusBar = False

End Sub


eg: ( this exmaple comes from the actual text file. there are a lot of these files in a folder hence i chose to use folders to search)



Running Script Line 2960: DELAY 2000

Running Script Line 2961: AIC 6 3.71 3.87 {LDC}

Result: FAIL 3.546

Running Script Line 2963: LDCCONSOLE w "dacout(0x62E6)rn"

Result: OK

Running Script Line 2964: DELAY 2000

Running Script Line 2965: AIC 6 4.2 4.36 {LDC}

Result: FAIL 4.000

Running Script Line 2967: LDCCONSOLE w "dacout(0x6E24)rn"

Result: OK

Running Script Line 2968: DELAY 2000

Running Script Line 2969: AIC 6 4.67 4.83 {LDC}

Result: FAIL 4.454

Running Script Line 2971: LDCCONSOLE w "dacout(0x796A)rn"

Result: OK

Running Script Line 2972: DELAY 2000

Running Script Line 2973: AIC 6 5.15 5.31 {LDC}

Result: FAIL 4.901

Running Script Line 2975: LDCCONSOLE w "dacout(0x84B5)rn"

Result: OK

Running Script Line 2976: DELAY 2000

Running Script Line 2977: AIC 6 5.62 5.78 {LDC}

Result: FAIL 5.348

Running Script Line 2979: LDCCONSOLE w "dacout(0x9005)rn"

Result: OK

Running Script Line 2980: DELAY 2000

Running Script Line 2981: AIC 6 6.1 6.26 {LDC}

Result: FAIL 5.792

Running Script Line 2983: LDCCONSOLE w "dacout(0x9B5B)rn"

Result: OK

Running Script Line 2984: DELAY 2000

Running Script Line 2985: AIC 6 6.57 6.73 {LDC}

Result: FAIL 6.235

Running Script Line 2987: LDCCONSOLE w "dacout(0xA6B5)rn"

Result: OK

Running Script Line 2988: DELAY 2000

Running Script Line 2989: AIC 6 7.05 7.21 {LDC}

Result: FAIL 6.681

Running Script Line 2991: LDCCONSOLE w "dacout(0xB215)rn"

Result: OK

Running Script Line 2992: DELAY 2000

Running Script Line 2993: AIC 6 7.54 7.7 {LDC}

Result: FAIL 7.126

Running Script Line 2995: LDCCONSOLE w "dacout(0xBD7A)rn"

Result: OK

Running Script Line 2996: DELAY 2000

Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572


in this upper example, the searched term will be "result: FAIL" and what i hope vba will print out will be the searched term plus the previous line for each searched term. i have already managed to do the searched term part. so for those which results are ok will be ignored. for those that failed, like the last script line, it will be printed out as:



Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572









share|improve this question




















  • 2




    What is the point of a Select Case with only a single case? What is the point of the GoTos? This seems like spaghetti code. It might help to rewrite it in a more structured way.
    – John Coleman
    Nov 20 at 2:21












  • A more constructive comment: I know that my own code became substantially better when I read Code Complete by Steve McConnell (one of the few computer books that I have read cover to cover). It is a bit dated now, but still a good guide for avoiding spaghetti code. Many of the examples are in VB6, so it is easy to apply the lessons to VBA.
    – John Coleman
    Nov 20 at 2:29










  • You should watch this series Excel VBA Introduction
    – TinMan
    Nov 20 at 2:33






  • 1




    As you learn to structure your code and abstract and name each "step" of the process, you'll find that GoTo jumps are pretty much always superfluous (On Error GoTo is an On Error statement, that's different): there's always a better, clearer, more efficient way to do things. Don't let yourself be blinded by the language and its vocabulary - procedures are verbs, values are nouns, make your own language. Don't just stitch code together - break down the problem in small steps. Then break each step down into smaller steps; identify inputs & outputs for each - then write the code.
    – Mathieu Guindon
    Nov 20 at 2:49










  • it looks like spaghetti code because of the tons of requirements i need to do but i have already placed them in order. there are more to this code but i did not include that due to it being irrelevant to the question. i had to use on error as it keeps popping up, it works even with the error.
    – Lee Hong Hui
    Nov 26 at 3:06















up vote
-1
down vote

favorite












Is there any way I can do to extract the previous sentence or the line above the searched word?



I am trying to extract it from multiple text files. so far I only managed to get the searched term to pop up, but not the text above it.



I am kinda new in VBA so I did pick a few things from others who have codes that solved my problems.



Public errors As Integer
Public X As Variant
Public Y As Variant
Public Sub testing()
Dim fldr As FileDialog
Dim sItem As String

Dim z As Variant
Dim ID As String
Dim reminder As String
Dim confirmation As String
z = Now()
start:

If UserForm1.CommandButton1 = True Then
Set X = CommandButton1.Name
End If



Y = Application.InputBox("Please enter your Employee ID", "For Verification Purposes", Type:=1)
Select Case Y
Case Y = ""
Exit Sub
End Select
ID = MsgBox("Is your Employee ID, " & (Y) & ", correct?", vbYesNo, "Confirm?")
Select Case ID
Case vbYes
GoTo foldersetting
Case vbNo
GoTo start
End Select




foldersetting:
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder for " & (X)
.AllowMultiSelect = True
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With

NextCode:
getfolder = sItem
Set fldr = Nothing

If getfolder = "" Then Exit Sub

Dim fso As Object
Dim fld As Object
Dim strSearch, strsearch1 As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

' On Error GoTo ErrHandler
Application.ScreenUpdating = False



'Change as desired
strPath = sItem '//////////////// <--- Change directory here \\\\\\\\\\\\
strSearch = "Result: FAIL" '///////////////// <--- Change term to search for here \\\\\\\\\\\
Set wOut = Worksheets.Add

Application.StatusBar = True

Application.StatusBar = "Please Wait..."

lRow = 1
With wOut
.Cells(lRow, 1) = "Type: " & (X)
.Cells(lRow, 2) = "Employee ID: " & (Y)
.Cells(lRow, 3) = "Date & Time of Extract: " & (z)
.Cells(lRow, 4) = "" 'Reserved for future use.
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.getfolder(strPath)




strFile = Dir(strPath & "*.txt") '<-- Currently searching all Log files. Change extension here
Do While strFile <> ""
Set wbk = Workbooks.Open _
(Filename:=strPath & "" & strFile, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)


For Each wks In wbk.Worksheets
Set rFound = wks.UsedRange.Find(strSearch)
If Not rFound Is Nothing Then
strFirstAddress = rFound.Address
End If
Do
If rFound Is Nothing Then
Exit Do
Else
lRow = lRow + 1
.Cells(lRow, 1) = rFound.Value

.Cells(lRow, 2) = wbk.Name


End If
Set rFound = wks.Cells.FindNext(after:=rFound)

Loop While strFirstAddress <> rFound.Address
Next


wbk.Close (False)
strFile = Dir


Loop
.Columns("A:D").EntireColumn.AutoFit


End With
errors = (ActiveSheet.UsedRange.Rows.Count - 1)


If (ActiveSheet.UsedRange.Rows.Count - 1) > 0 Then
MsgBox "There are " & (ActiveSheet.UsedRange.Rows.Count - 1) & " Failures Found!", vbCritical, "Warning"
ElseIf (ActiveSheet.UsedRange.Rows.Count - 1) = 0 Then
MsgBox "No errors found.", vbInformation, "No Errors"
Dim sh As Worksheet
Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
End If

Dim lastrow As Long
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 2

ActiveSheet.Cells(lastrow, "A").Value = "Number of Failures: " &
(ActiveSheet.UsedRange.Rows.Count - 1)
On Error GoTo calling
Dim rngData As Range
Dim strData As String
Dim strTempFile As String

' copy some range values
Set rngData = wOut.Range("A:D")
rngData.Copy

' get the clipboard data
' magic code for is for early binding to MSForms.DataObject
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.GetFromClipboard
strData = .GetText
End With

' write to temp file
strTempFile = "D:temp.txt"
With CreateObject("Scripting.FileSystemObject")
' true to overwrite existing temp file
.CreateTextFile(strTempFile, True).Write strData
End With

' open notepad with tempfile
Shell "cmd /c ""notepad.exe """ & strTempFile & """", vbHide
calling:
Call log

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True

Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
Application.StatusBar = False

End Sub


eg: ( this exmaple comes from the actual text file. there are a lot of these files in a folder hence i chose to use folders to search)



Running Script Line 2960: DELAY 2000

Running Script Line 2961: AIC 6 3.71 3.87 {LDC}

Result: FAIL 3.546

Running Script Line 2963: LDCCONSOLE w "dacout(0x62E6)rn"

Result: OK

Running Script Line 2964: DELAY 2000

Running Script Line 2965: AIC 6 4.2 4.36 {LDC}

Result: FAIL 4.000

Running Script Line 2967: LDCCONSOLE w "dacout(0x6E24)rn"

Result: OK

Running Script Line 2968: DELAY 2000

Running Script Line 2969: AIC 6 4.67 4.83 {LDC}

Result: FAIL 4.454

Running Script Line 2971: LDCCONSOLE w "dacout(0x796A)rn"

Result: OK

Running Script Line 2972: DELAY 2000

Running Script Line 2973: AIC 6 5.15 5.31 {LDC}

Result: FAIL 4.901

Running Script Line 2975: LDCCONSOLE w "dacout(0x84B5)rn"

Result: OK

Running Script Line 2976: DELAY 2000

Running Script Line 2977: AIC 6 5.62 5.78 {LDC}

Result: FAIL 5.348

Running Script Line 2979: LDCCONSOLE w "dacout(0x9005)rn"

Result: OK

Running Script Line 2980: DELAY 2000

Running Script Line 2981: AIC 6 6.1 6.26 {LDC}

Result: FAIL 5.792

Running Script Line 2983: LDCCONSOLE w "dacout(0x9B5B)rn"

Result: OK

Running Script Line 2984: DELAY 2000

Running Script Line 2985: AIC 6 6.57 6.73 {LDC}

Result: FAIL 6.235

Running Script Line 2987: LDCCONSOLE w "dacout(0xA6B5)rn"

Result: OK

Running Script Line 2988: DELAY 2000

Running Script Line 2989: AIC 6 7.05 7.21 {LDC}

Result: FAIL 6.681

Running Script Line 2991: LDCCONSOLE w "dacout(0xB215)rn"

Result: OK

Running Script Line 2992: DELAY 2000

Running Script Line 2993: AIC 6 7.54 7.7 {LDC}

Result: FAIL 7.126

Running Script Line 2995: LDCCONSOLE w "dacout(0xBD7A)rn"

Result: OK

Running Script Line 2996: DELAY 2000

Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572


in this upper example, the searched term will be "result: FAIL" and what i hope vba will print out will be the searched term plus the previous line for each searched term. i have already managed to do the searched term part. so for those which results are ok will be ignored. for those that failed, like the last script line, it will be printed out as:



Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572









share|improve this question




















  • 2




    What is the point of a Select Case with only a single case? What is the point of the GoTos? This seems like spaghetti code. It might help to rewrite it in a more structured way.
    – John Coleman
    Nov 20 at 2:21












  • A more constructive comment: I know that my own code became substantially better when I read Code Complete by Steve McConnell (one of the few computer books that I have read cover to cover). It is a bit dated now, but still a good guide for avoiding spaghetti code. Many of the examples are in VB6, so it is easy to apply the lessons to VBA.
    – John Coleman
    Nov 20 at 2:29










  • You should watch this series Excel VBA Introduction
    – TinMan
    Nov 20 at 2:33






  • 1




    As you learn to structure your code and abstract and name each "step" of the process, you'll find that GoTo jumps are pretty much always superfluous (On Error GoTo is an On Error statement, that's different): there's always a better, clearer, more efficient way to do things. Don't let yourself be blinded by the language and its vocabulary - procedures are verbs, values are nouns, make your own language. Don't just stitch code together - break down the problem in small steps. Then break each step down into smaller steps; identify inputs & outputs for each - then write the code.
    – Mathieu Guindon
    Nov 20 at 2:49










  • it looks like spaghetti code because of the tons of requirements i need to do but i have already placed them in order. there are more to this code but i did not include that due to it being irrelevant to the question. i had to use on error as it keeps popping up, it works even with the error.
    – Lee Hong Hui
    Nov 26 at 3:06













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











Is there any way I can do to extract the previous sentence or the line above the searched word?



I am trying to extract it from multiple text files. so far I only managed to get the searched term to pop up, but not the text above it.



I am kinda new in VBA so I did pick a few things from others who have codes that solved my problems.



Public errors As Integer
Public X As Variant
Public Y As Variant
Public Sub testing()
Dim fldr As FileDialog
Dim sItem As String

Dim z As Variant
Dim ID As String
Dim reminder As String
Dim confirmation As String
z = Now()
start:

If UserForm1.CommandButton1 = True Then
Set X = CommandButton1.Name
End If



Y = Application.InputBox("Please enter your Employee ID", "For Verification Purposes", Type:=1)
Select Case Y
Case Y = ""
Exit Sub
End Select
ID = MsgBox("Is your Employee ID, " & (Y) & ", correct?", vbYesNo, "Confirm?")
Select Case ID
Case vbYes
GoTo foldersetting
Case vbNo
GoTo start
End Select




foldersetting:
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder for " & (X)
.AllowMultiSelect = True
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With

NextCode:
getfolder = sItem
Set fldr = Nothing

If getfolder = "" Then Exit Sub

Dim fso As Object
Dim fld As Object
Dim strSearch, strsearch1 As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

' On Error GoTo ErrHandler
Application.ScreenUpdating = False



'Change as desired
strPath = sItem '//////////////// <--- Change directory here \\\\\\\\\\\\
strSearch = "Result: FAIL" '///////////////// <--- Change term to search for here \\\\\\\\\\\
Set wOut = Worksheets.Add

Application.StatusBar = True

Application.StatusBar = "Please Wait..."

lRow = 1
With wOut
.Cells(lRow, 1) = "Type: " & (X)
.Cells(lRow, 2) = "Employee ID: " & (Y)
.Cells(lRow, 3) = "Date & Time of Extract: " & (z)
.Cells(lRow, 4) = "" 'Reserved for future use.
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.getfolder(strPath)




strFile = Dir(strPath & "*.txt") '<-- Currently searching all Log files. Change extension here
Do While strFile <> ""
Set wbk = Workbooks.Open _
(Filename:=strPath & "" & strFile, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)


For Each wks In wbk.Worksheets
Set rFound = wks.UsedRange.Find(strSearch)
If Not rFound Is Nothing Then
strFirstAddress = rFound.Address
End If
Do
If rFound Is Nothing Then
Exit Do
Else
lRow = lRow + 1
.Cells(lRow, 1) = rFound.Value

.Cells(lRow, 2) = wbk.Name


End If
Set rFound = wks.Cells.FindNext(after:=rFound)

Loop While strFirstAddress <> rFound.Address
Next


wbk.Close (False)
strFile = Dir


Loop
.Columns("A:D").EntireColumn.AutoFit


End With
errors = (ActiveSheet.UsedRange.Rows.Count - 1)


If (ActiveSheet.UsedRange.Rows.Count - 1) > 0 Then
MsgBox "There are " & (ActiveSheet.UsedRange.Rows.Count - 1) & " Failures Found!", vbCritical, "Warning"
ElseIf (ActiveSheet.UsedRange.Rows.Count - 1) = 0 Then
MsgBox "No errors found.", vbInformation, "No Errors"
Dim sh As Worksheet
Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
End If

Dim lastrow As Long
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 2

ActiveSheet.Cells(lastrow, "A").Value = "Number of Failures: " &
(ActiveSheet.UsedRange.Rows.Count - 1)
On Error GoTo calling
Dim rngData As Range
Dim strData As String
Dim strTempFile As String

' copy some range values
Set rngData = wOut.Range("A:D")
rngData.Copy

' get the clipboard data
' magic code for is for early binding to MSForms.DataObject
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.GetFromClipboard
strData = .GetText
End With

' write to temp file
strTempFile = "D:temp.txt"
With CreateObject("Scripting.FileSystemObject")
' true to overwrite existing temp file
.CreateTextFile(strTempFile, True).Write strData
End With

' open notepad with tempfile
Shell "cmd /c ""notepad.exe """ & strTempFile & """", vbHide
calling:
Call log

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True

Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
Application.StatusBar = False

End Sub


eg: ( this exmaple comes from the actual text file. there are a lot of these files in a folder hence i chose to use folders to search)



Running Script Line 2960: DELAY 2000

Running Script Line 2961: AIC 6 3.71 3.87 {LDC}

Result: FAIL 3.546

Running Script Line 2963: LDCCONSOLE w "dacout(0x62E6)rn"

Result: OK

Running Script Line 2964: DELAY 2000

Running Script Line 2965: AIC 6 4.2 4.36 {LDC}

Result: FAIL 4.000

Running Script Line 2967: LDCCONSOLE w "dacout(0x6E24)rn"

Result: OK

Running Script Line 2968: DELAY 2000

Running Script Line 2969: AIC 6 4.67 4.83 {LDC}

Result: FAIL 4.454

Running Script Line 2971: LDCCONSOLE w "dacout(0x796A)rn"

Result: OK

Running Script Line 2972: DELAY 2000

Running Script Line 2973: AIC 6 5.15 5.31 {LDC}

Result: FAIL 4.901

Running Script Line 2975: LDCCONSOLE w "dacout(0x84B5)rn"

Result: OK

Running Script Line 2976: DELAY 2000

Running Script Line 2977: AIC 6 5.62 5.78 {LDC}

Result: FAIL 5.348

Running Script Line 2979: LDCCONSOLE w "dacout(0x9005)rn"

Result: OK

Running Script Line 2980: DELAY 2000

Running Script Line 2981: AIC 6 6.1 6.26 {LDC}

Result: FAIL 5.792

Running Script Line 2983: LDCCONSOLE w "dacout(0x9B5B)rn"

Result: OK

Running Script Line 2984: DELAY 2000

Running Script Line 2985: AIC 6 6.57 6.73 {LDC}

Result: FAIL 6.235

Running Script Line 2987: LDCCONSOLE w "dacout(0xA6B5)rn"

Result: OK

Running Script Line 2988: DELAY 2000

Running Script Line 2989: AIC 6 7.05 7.21 {LDC}

Result: FAIL 6.681

Running Script Line 2991: LDCCONSOLE w "dacout(0xB215)rn"

Result: OK

Running Script Line 2992: DELAY 2000

Running Script Line 2993: AIC 6 7.54 7.7 {LDC}

Result: FAIL 7.126

Running Script Line 2995: LDCCONSOLE w "dacout(0xBD7A)rn"

Result: OK

Running Script Line 2996: DELAY 2000

Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572


in this upper example, the searched term will be "result: FAIL" and what i hope vba will print out will be the searched term plus the previous line for each searched term. i have already managed to do the searched term part. so for those which results are ok will be ignored. for those that failed, like the last script line, it will be printed out as:



Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572









share|improve this question















Is there any way I can do to extract the previous sentence or the line above the searched word?



I am trying to extract it from multiple text files. so far I only managed to get the searched term to pop up, but not the text above it.



I am kinda new in VBA so I did pick a few things from others who have codes that solved my problems.



Public errors As Integer
Public X As Variant
Public Y As Variant
Public Sub testing()
Dim fldr As FileDialog
Dim sItem As String

Dim z As Variant
Dim ID As String
Dim reminder As String
Dim confirmation As String
z = Now()
start:

If UserForm1.CommandButton1 = True Then
Set X = CommandButton1.Name
End If



Y = Application.InputBox("Please enter your Employee ID", "For Verification Purposes", Type:=1)
Select Case Y
Case Y = ""
Exit Sub
End Select
ID = MsgBox("Is your Employee ID, " & (Y) & ", correct?", vbYesNo, "Confirm?")
Select Case ID
Case vbYes
GoTo foldersetting
Case vbNo
GoTo start
End Select




foldersetting:
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder for " & (X)
.AllowMultiSelect = True
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With

NextCode:
getfolder = sItem
Set fldr = Nothing

If getfolder = "" Then Exit Sub

Dim fso As Object
Dim fld As Object
Dim strSearch, strsearch1 As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim lRow As Long
Dim rFound As Range
Dim strFirstAddress As String

' On Error GoTo ErrHandler
Application.ScreenUpdating = False



'Change as desired
strPath = sItem '//////////////// <--- Change directory here \\\\\\\\\\\\
strSearch = "Result: FAIL" '///////////////// <--- Change term to search for here \\\\\\\\\\\
Set wOut = Worksheets.Add

Application.StatusBar = True

Application.StatusBar = "Please Wait..."

lRow = 1
With wOut
.Cells(lRow, 1) = "Type: " & (X)
.Cells(lRow, 2) = "Employee ID: " & (Y)
.Cells(lRow, 3) = "Date & Time of Extract: " & (z)
.Cells(lRow, 4) = "" 'Reserved for future use.
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.getfolder(strPath)




strFile = Dir(strPath & "*.txt") '<-- Currently searching all Log files. Change extension here
Do While strFile <> ""
Set wbk = Workbooks.Open _
(Filename:=strPath & "" & strFile, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)


For Each wks In wbk.Worksheets
Set rFound = wks.UsedRange.Find(strSearch)
If Not rFound Is Nothing Then
strFirstAddress = rFound.Address
End If
Do
If rFound Is Nothing Then
Exit Do
Else
lRow = lRow + 1
.Cells(lRow, 1) = rFound.Value

.Cells(lRow, 2) = wbk.Name


End If
Set rFound = wks.Cells.FindNext(after:=rFound)

Loop While strFirstAddress <> rFound.Address
Next


wbk.Close (False)
strFile = Dir


Loop
.Columns("A:D").EntireColumn.AutoFit


End With
errors = (ActiveSheet.UsedRange.Rows.Count - 1)


If (ActiveSheet.UsedRange.Rows.Count - 1) > 0 Then
MsgBox "There are " & (ActiveSheet.UsedRange.Rows.Count - 1) & " Failures Found!", vbCritical, "Warning"
ElseIf (ActiveSheet.UsedRange.Rows.Count - 1) = 0 Then
MsgBox "No errors found.", vbInformation, "No Errors"
Dim sh As Worksheet
Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
End If

Dim lastrow As Long
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 2

ActiveSheet.Cells(lastrow, "A").Value = "Number of Failures: " &
(ActiveSheet.UsedRange.Rows.Count - 1)
On Error GoTo calling
Dim rngData As Range
Dim strData As String
Dim strTempFile As String

' copy some range values
Set rngData = wOut.Range("A:D")
rngData.Copy

' get the clipboard data
' magic code for is for early binding to MSForms.DataObject
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.GetFromClipboard
strData = .GetText
End With

' write to temp file
strTempFile = "D:temp.txt"
With CreateObject("Scripting.FileSystemObject")
' true to overwrite existing temp file
.CreateTextFile(strTempFile, True).Write strData
End With

' open notepad with tempfile
Shell "cmd /c ""notepad.exe """ & strTempFile & """", vbHide
calling:
Call log

ExitHandler:
Set wOut = Nothing
Set wks = Nothing
Set wbk = Nothing
Set fld = Nothing
Set fso = Nothing
Application.ScreenUpdating = True

Application.DisplayAlerts = False
For Each sh In Worksheets
Select Case sh.CodeName
Case "Sheet1", "Sheet2"
Case Else
sh.Delete
End Select
Next sh
Application.DisplayAlerts = True
Application.StatusBar = False

End Sub


eg: ( this exmaple comes from the actual text file. there are a lot of these files in a folder hence i chose to use folders to search)



Running Script Line 2960: DELAY 2000

Running Script Line 2961: AIC 6 3.71 3.87 {LDC}

Result: FAIL 3.546

Running Script Line 2963: LDCCONSOLE w "dacout(0x62E6)rn"

Result: OK

Running Script Line 2964: DELAY 2000

Running Script Line 2965: AIC 6 4.2 4.36 {LDC}

Result: FAIL 4.000

Running Script Line 2967: LDCCONSOLE w "dacout(0x6E24)rn"

Result: OK

Running Script Line 2968: DELAY 2000

Running Script Line 2969: AIC 6 4.67 4.83 {LDC}

Result: FAIL 4.454

Running Script Line 2971: LDCCONSOLE w "dacout(0x796A)rn"

Result: OK

Running Script Line 2972: DELAY 2000

Running Script Line 2973: AIC 6 5.15 5.31 {LDC}

Result: FAIL 4.901

Running Script Line 2975: LDCCONSOLE w "dacout(0x84B5)rn"

Result: OK

Running Script Line 2976: DELAY 2000

Running Script Line 2977: AIC 6 5.62 5.78 {LDC}

Result: FAIL 5.348

Running Script Line 2979: LDCCONSOLE w "dacout(0x9005)rn"

Result: OK

Running Script Line 2980: DELAY 2000

Running Script Line 2981: AIC 6 6.1 6.26 {LDC}

Result: FAIL 5.792

Running Script Line 2983: LDCCONSOLE w "dacout(0x9B5B)rn"

Result: OK

Running Script Line 2984: DELAY 2000

Running Script Line 2985: AIC 6 6.57 6.73 {LDC}

Result: FAIL 6.235

Running Script Line 2987: LDCCONSOLE w "dacout(0xA6B5)rn"

Result: OK

Running Script Line 2988: DELAY 2000

Running Script Line 2989: AIC 6 7.05 7.21 {LDC}

Result: FAIL 6.681

Running Script Line 2991: LDCCONSOLE w "dacout(0xB215)rn"

Result: OK

Running Script Line 2992: DELAY 2000

Running Script Line 2993: AIC 6 7.54 7.7 {LDC}

Result: FAIL 7.126

Running Script Line 2995: LDCCONSOLE w "dacout(0xBD7A)rn"

Result: OK

Running Script Line 2996: DELAY 2000

Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572


in this upper example, the searched term will be "result: FAIL" and what i hope vba will print out will be the searched term plus the previous line for each searched term. i have already managed to do the searched term part. so for those which results are ok will be ignored. for those that failed, like the last script line, it will be printed out as:



Running Script Line 2997: AIC 6 8.02 8.18 {LDC}

Result: FAIL 7.572






excel vba






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 7:27

























asked Nov 20 at 1:57









Lee Hong Hui

13




13








  • 2




    What is the point of a Select Case with only a single case? What is the point of the GoTos? This seems like spaghetti code. It might help to rewrite it in a more structured way.
    – John Coleman
    Nov 20 at 2:21












  • A more constructive comment: I know that my own code became substantially better when I read Code Complete by Steve McConnell (one of the few computer books that I have read cover to cover). It is a bit dated now, but still a good guide for avoiding spaghetti code. Many of the examples are in VB6, so it is easy to apply the lessons to VBA.
    – John Coleman
    Nov 20 at 2:29










  • You should watch this series Excel VBA Introduction
    – TinMan
    Nov 20 at 2:33






  • 1




    As you learn to structure your code and abstract and name each "step" of the process, you'll find that GoTo jumps are pretty much always superfluous (On Error GoTo is an On Error statement, that's different): there's always a better, clearer, more efficient way to do things. Don't let yourself be blinded by the language and its vocabulary - procedures are verbs, values are nouns, make your own language. Don't just stitch code together - break down the problem in small steps. Then break each step down into smaller steps; identify inputs & outputs for each - then write the code.
    – Mathieu Guindon
    Nov 20 at 2:49










  • it looks like spaghetti code because of the tons of requirements i need to do but i have already placed them in order. there are more to this code but i did not include that due to it being irrelevant to the question. i had to use on error as it keeps popping up, it works even with the error.
    – Lee Hong Hui
    Nov 26 at 3:06














  • 2




    What is the point of a Select Case with only a single case? What is the point of the GoTos? This seems like spaghetti code. It might help to rewrite it in a more structured way.
    – John Coleman
    Nov 20 at 2:21












  • A more constructive comment: I know that my own code became substantially better when I read Code Complete by Steve McConnell (one of the few computer books that I have read cover to cover). It is a bit dated now, but still a good guide for avoiding spaghetti code. Many of the examples are in VB6, so it is easy to apply the lessons to VBA.
    – John Coleman
    Nov 20 at 2:29










  • You should watch this series Excel VBA Introduction
    – TinMan
    Nov 20 at 2:33






  • 1




    As you learn to structure your code and abstract and name each "step" of the process, you'll find that GoTo jumps are pretty much always superfluous (On Error GoTo is an On Error statement, that's different): there's always a better, clearer, more efficient way to do things. Don't let yourself be blinded by the language and its vocabulary - procedures are verbs, values are nouns, make your own language. Don't just stitch code together - break down the problem in small steps. Then break each step down into smaller steps; identify inputs & outputs for each - then write the code.
    – Mathieu Guindon
    Nov 20 at 2:49










  • it looks like spaghetti code because of the tons of requirements i need to do but i have already placed them in order. there are more to this code but i did not include that due to it being irrelevant to the question. i had to use on error as it keeps popping up, it works even with the error.
    – Lee Hong Hui
    Nov 26 at 3:06








2




2




What is the point of a Select Case with only a single case? What is the point of the GoTos? This seems like spaghetti code. It might help to rewrite it in a more structured way.
– John Coleman
Nov 20 at 2:21






What is the point of a Select Case with only a single case? What is the point of the GoTos? This seems like spaghetti code. It might help to rewrite it in a more structured way.
– John Coleman
Nov 20 at 2:21














A more constructive comment: I know that my own code became substantially better when I read Code Complete by Steve McConnell (one of the few computer books that I have read cover to cover). It is a bit dated now, but still a good guide for avoiding spaghetti code. Many of the examples are in VB6, so it is easy to apply the lessons to VBA.
– John Coleman
Nov 20 at 2:29




A more constructive comment: I know that my own code became substantially better when I read Code Complete by Steve McConnell (one of the few computer books that I have read cover to cover). It is a bit dated now, but still a good guide for avoiding spaghetti code. Many of the examples are in VB6, so it is easy to apply the lessons to VBA.
– John Coleman
Nov 20 at 2:29












You should watch this series Excel VBA Introduction
– TinMan
Nov 20 at 2:33




You should watch this series Excel VBA Introduction
– TinMan
Nov 20 at 2:33




1




1




As you learn to structure your code and abstract and name each "step" of the process, you'll find that GoTo jumps are pretty much always superfluous (On Error GoTo is an On Error statement, that's different): there's always a better, clearer, more efficient way to do things. Don't let yourself be blinded by the language and its vocabulary - procedures are verbs, values are nouns, make your own language. Don't just stitch code together - break down the problem in small steps. Then break each step down into smaller steps; identify inputs & outputs for each - then write the code.
– Mathieu Guindon
Nov 20 at 2:49




As you learn to structure your code and abstract and name each "step" of the process, you'll find that GoTo jumps are pretty much always superfluous (On Error GoTo is an On Error statement, that's different): there's always a better, clearer, more efficient way to do things. Don't let yourself be blinded by the language and its vocabulary - procedures are verbs, values are nouns, make your own language. Don't just stitch code together - break down the problem in small steps. Then break each step down into smaller steps; identify inputs & outputs for each - then write the code.
– Mathieu Guindon
Nov 20 at 2:49












it looks like spaghetti code because of the tons of requirements i need to do but i have already placed them in order. there are more to this code but i did not include that due to it being irrelevant to the question. i had to use on error as it keeps popping up, it works even with the error.
– Lee Hong Hui
Nov 26 at 3:06




it looks like spaghetti code because of the tons of requirements i need to do but i have already placed them in order. there are more to this code but i did not include that due to it being irrelevant to the question. i had to use on error as it keeps popping up, it works even with the error.
– Lee Hong Hui
Nov 26 at 3:06

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385152%2fextracting-searched-term-and-previous-line-vba%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53385152%2fextracting-searched-term-and-previous-line-vba%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

Refactoring coordinates for Minecraft Pi buildings written in Python