I am trying to build a routine that opens each excel file in a folder, searches ( using the Find command) for the string “# Issues”, selects the entire row where it finds the string, then delete that row and the next two additional rows. It runs successfully the first iteration, but fails the second time through the loop st the Find command.
I have struggled with this failure on second iteration several times with different code, making me think I am making some kind of mistake in defining my objects.
My code:
Function CleanFilesInAGivenFolder(strFolder As String, _
strCellLoc As String, _
strNewValue As String)
Dim strReportType As String
Dim myfile
Dim mypath
Dim strPathFileName As String
If Right(strFolder, 1) <> "\" Then
strFolder = strFolder & "\"
End If
mypath = strFolder
ChDir (strFolder)
myfile = Dir(mypath)
ChDir (mypath)
myfile = Dir("")
Do While myfile <> ""
'Format the excel report
strPathFileName = mypath & myfile
Dim appExcel As Excel.Application
Dim wkb As Excel.Workbook
Dim sht As Worksheet
Dim rng As Range
Dim FoundCell As Range
'Define the file and location
strPathFileName = mypath & myfile
'define the excel session
Set appExcel = New Excel.Application
appExcel.Visible = True
'Define the workbook
Set wkb = appExcel.Workbooks.Open(strPathFileName)
'Make sheet 1 the active sheet
Set wkb = ActiveWorkbook
Set sht = ActiveSheet
'Find the row with "# Issues" in column A,
'delete row this next 2 rows
'Only works the first iteration of loop
With sht
Set FoundCell = Selection.Find(What:="# Issues", _
After:=[a1],
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
ActiveCell.EntireRow.Select
End With
If Not FoundCell Is Nothing Then
Selection.Delete Shift:=xlUp
Selection.Delete Shift:=xlUp
Selection.Delete Shift:=xlUp
End If
'Clear Objects
appExcel.DisplayAlerts = False
wkb.Save
wkb.Close
appExcel.DisplayAlerts = True
Set rng = Nothing
Set sht = Nothing
Set wkb = Nothing
appExcel.Quit
Set appExcel = Nothing
myfile = Dir()
Loop
End Function