IFERROR in in this macro? - excel

The problem is that when I change the value in I16 or I17 I get an error. How
can I prevent this error from happening?
I check in I16 and I17 for the sheetnames, because every week an updated sheet comes available.
Thank you
Sub Compare()
Call compareSheets(range("I16").Value, range("I17").Value)
End Sub
Sub compareSheets(Sofon As String, Sofon2 As String)
Dim mycell As range
Dim mydiffs As Integer
For Each mycell In ActiveWorkbook.Worksheets(Sofon2).range("M:M")
If Not mycell.Value = ActiveWorkbook.Worksheets(Sofon).Cells(mycell.Row, mycell.Column).Value Then
mycell.Interior.Color = vbYellow
mydiffs = mydiffs + 1
End If
Next
MsgBox mydiffs & " differences found in Column M (Salesman)", vbInformation
ActiveWorkbook.Sheets(Sofon2).Select
End Sub

Just to show what I was thinking.
I agree with puzzlepiece87 that On Error is finicky, but with something this simple I would use it to avoid the excess loops.
Sub compareSheets(Sofon As String, Sofon2 As String)
Dim mycell As Range
Dim mydiffs As Integer
On Error GoTo nosheet
For Each mycell In ActiveWorkbook.Worksheets(Sofon2).Range("M:M")
If Not mycell.Value = ActiveWorkbook.Worksheets(Sofon).Cells(mycell.Row, mycell.Column).Value Then
mycell.Interior.Color = vbYellow
mydiffs = mydiffs + 1
End If
Next
MsgBox mydiffs & " differences found in Column M (Salesman)", vbInformation
ActiveWorkbook.Sheets(Sofon2).Select
Exit Sub
nosheet:
If Err.Number = 9 Then
MsgBox "One or both sheets do not exist"
Else
MsgBox Err.Description
End If
End Sub

Since the OP wanted an ISERROR type of solution, I decided to post the code which incorporates a function to check if a sheet exists in a workbook. The concept is similar to answers already posted, but it keeps any On Error statements strictly inside the function and uses regular code blocks to evaluate errors.
Sub Compare()
Dim bGo As Boolean
Dim s1 As String, s2 As String
s1 = Range("I16").Value2
s2 = Range("I17").Value2
If Not WorksheetExist(s1) Then
bGo = False
MsgBox "The sheet " & s1 & " does not exist in this workbook."
End If
If Not WorksheetExist(s2) Then
bGo = False
MsgBox "The sheet " & s2 & " does not exist in this workbook."
End If
If bGo Then compareSheets s1, s2
End Sub
Function WorksheetExist(sName As String, Optional wb As Workbook) As Boolean
Dim wbCheck As Workbook, ws As Worksheet
If wb Is Nothing Then Set wbCheck = ThisWorkbook Else: Set wbCheck = wb
On Error Resume Next
Set ws = wbCheck.Sheets(sName)
On Error GoTo 0
If Not ws Is Nothing Then WorksheetExist = True Else: WorksheetExist = False
End Function
And, based on #puzzlepiece87 methodology, here is an improved WorksheetExist Function that eliminates of On Error statements altogether.
Function WorksheetExist(sName As String, Optional wb As Workbook) As Boolean
Dim wbCheck As Workbook, ws As Worksheet
If wb Is Nothing Then Set wbCheck = ThisWorkbook Else: Set wbCheck = wb
WorksheetExist = False
For Each ws In wbCheck.Worksheets
If ws.Name = sName Then
WorksheetExist = True
Exit For
End If
Next
End Function

You could use something similar to this to call compareSheets. It will warn you if either of the two ranges do not correspond to sheet names and won't call compareSheets if true.
Dim Sheet1 As Worksheet
Dim boolI16SheetCheck As Boolean
Dim boolI17SheetCheck As Boolean
boolI16SheetCheck = False
boolI17SheetCheck = False
For Each Sheet1 in ActiveWorkbook.Worksheets
If Sheet1.Name = Activesheet.Range("I16").Value Then boolI16SheetCheck = True
If Sheet1.Name = Activesheet.Range("I17").Value Then boolI17SheetCheck = True
If boolI16SheetCheck = True And boolI17SheetCheck = True Then
Call compareSheets(range("I16").Value, range("I17").Value)
Exit Sub
End If
Next Sheet1
If boolI16SheetCheck = False Then
If boolI17SheetCheck = False Then
Msgbox "Neither I16 nor I17 sheet found."
Else
Msgbox "I16 sheet not found."
End If
Else
Msgbox "I17 sheet not found."
End If
End Sub

Related

Silently VBA add new Excel worksheet without screen update

I'm adding a new worksheet to my workbook with
Application.ScreenUpdating = False
SheetExists = False
For Each WS In Worksheets
If WS.Name = "BLANK" Then
SheetExists = True
End If
Next WS
If Not SheetExists Then
Sheets.Add
ActiveSheet.Name = "BLANK"
End If
Is there any way to sheets.add silently without bringing focus to or activating the new added sheet? I just want to stay on the sheet (ie. Sheet1) that is currently active and add the new sheet in the background.
Thanks
At first, things look simple but there are a few things to consider:
There could be more sheets selected before running the code
The selected sheet(s) could be Chart sheet(s)
The Workbook can be protected
You might not want to set Application.ScreenUpdating = True at the end of the method because you might be running this from within another method that still needs it off
Restoring selection can only happen if the proper window is activated
You could use this method:
Sub AddWorksheet(ByVal targetBook As Workbook, ByVal sheetname As String)
Const methodName As String = "AddWorksheet"
'Do input checks
If targetBook Is Nothing Then
Err.Raise 91, methodName, "Target Book not set"
ElseIf sheetname = vbNullString Then
Err.Raise 5, methodName, "Sheet name cannot be blank"
ElseIf Len(sheetname) > 31 Then
Err.Raise 5, methodName, "Sheet name cannot exceed 31 characters"
Else
Dim arrForbiddenChars() As Variant
Dim forbiddenChar As Variant
arrForbiddenChars = Array(":", "\", "/", "?", "*", "[", "]")
For Each forbiddenChar In arrForbiddenChars
If InStr(1, sheetname, forbiddenChar) > 0 Then
Err.Raise 5, methodName, "Sheet name cannot contain characters: : \ / ? * [ or ]"
End If
Next forbiddenChar
End If
Dim alreadyExists As Boolean
'Check if a sheet already exists with the desired name
On Error Resume Next
alreadyExists = Not (targetBook.Sheets(sheetname) Is Nothing)
On Error GoTo 0
If alreadyExists Then
MsgBox "A sheet named <" & sheetname & "> already exists!", vbInformation, "Cancelled" 'Can remove
Exit Sub
End If
'Check if Workbook is protected
If targetBook.ProtectStructure Then
'Maybe write code to ask for password and then unprotect
'
'
'Or simply exit
MsgBox "Workbook is protected. Cannot add sheet", vbInformation, "Cancelled"
Exit Sub
End If
Dim bookActiveWindow As Window
Dim appActiveWindow As Window
Dim selectedSheets As Sheets
Dim screenUpdate As Boolean
Dim newWSheet As Worksheet
'Store state
Set bookActiveWindow = targetBook.Windows(1)
Set appActiveWindow = Application.ActiveWindow 'Can be different from the target book window
Set selectedSheets = bookActiveWindow.selectedSheets
screenUpdate = Application.ScreenUpdating
'Do main logic
screenUpdate = False
If bookActiveWindow.Hwnd <> Application.ActiveWindow.Hwnd Then
bookActiveWindow.Activate
End If
If selectedSheets.Count > 1 Then selectedSheets(1).Select Replace:=True
Set newWSheet = targetBook.Worksheets.Add
newWSheet.Name = sheetname
'Restore state
selectedSheets.Select Replace:=True
If appActiveWindow.Hwnd <> Application.ActiveWindow.Hwnd Then
appActiveWindow.Activate
End If
Application.ScreenUpdating = screenUpdate
End Sub
If you want the book containing the code then you can call with:
Sub Test()
AddWorksheet ThisWorkbook, "BLANK"
End Sub
or, if you want the currently active book (assuming you are running this from an add-in) then you can call with:
Sub Test()
AddWorksheet ActiveWorkbook, "BLANK"
End Sub
or any other book depending on your needs.
Just remember who was active:
Sub ytrewq()
Dim wsh As Worksheet, SheetsExist As Boolean
Set wsh = ActiveSheet
Application.ScreenUpdating = False
SheetExists = False
For Each ws In Worksheets
If ws.Name = "BLANK" Then
SheetExists = True
End If
Next ws
If Not SheetExists Then
Sheets.Add
ActiveSheet.Name = "BLANK"
End If
wsh.Activate
Application.ScreenUpdating = False
End Sub

In VBA how to keep two worksheets and delete other sheets

Hi everyone! I'm trying to write a method in VBA to keep 2 worksheets and delete others at the same time.
I already did the one that will keep one worksheet and delete others like this:
Sub delete_all_pages_except_main()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Application.DisplayAlerts = False
If ws.Name <> "Home Page" Then
ws.Delete
End If
Next ws
End Sub
And I try to write it like this
If (ws.Name <> "Home Page" Or ws.Name <> "Data")
But VBA would accept it.
Can you guys help? Thank you.
This should do
Sub delete_all_pages_except_main()
Dim ws As Worksheet
Dim arr As Variant
Dim boo As Boolean
Application.DisplayAlerts = False
arr = Array("Home Page", "Data")
For Each ws In ThisWorkbook.Worksheets
boo = NoDel(ws.Name, arr)
If boo <> True Then ws.Delete
Next ws
Application.DisplayAlerts = True
End Sub
Function NoDel(ws As String, warr As Variant) As Boolean
NoDel = False
For i = LBound(warr, 1) To UBound(warr, 1)
If warr(i) = ws Then NoDel = True
Next i
End Function
Delete Sheets With Exceptions
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: In a specified workbook, writes all the sheet names '
' not specified in an Exceptions array to a Result array, and '
' using the Result array deletes all the sheets in one go. '
' Remarks: This solution applies to worksheets and chartsheets. '
' Since there is no Sheet object, the For Next loop (instead '
' of the For Each Next loop) and the Object type have '
' to be used. '
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub deleteSheets(Book As Workbook, Exceptions As Variant)
' Program
Dim SheetsCount As Long: SheetsCount = Book.Sheets.Count
Dim Result As Variant: ReDim Result(SheetsCount)
Dim sh As Object, i As Long, j As Long
j = -1
For i = 1 To SheetsCount: GoSub checkName: Next i
If j = -1 Then GoTo NothingToDelete
If j = SheetsCount - 1 Then GoTo NoExceptions
GoSub deleteSheetsInOneGo
MsgBox "Deleted '" & j + 1 & "' sheets.", vbInformation, "Success"
Exit Sub
' Subroutines
checkName:
Set sh = Book.Sheets(i)
If IsError(Application.Match(sh.Name, Exceptions, 0)) Then
j = j + 1
Result(j) = sh.Name
End If
Return
deleteSheetsInOneGo:
ReDim Preserve Result(j)
Application.DisplayAlerts = False
Book.Sheets(Result).Delete
Application.DisplayAlerts = True
Return
' Labels
NothingToDelete:
MsgBox "Sheets already deleted.", vbCritical, "Nothing to Delete"
Exit Sub
NoExceptions:
MsgBox "Cannot delete all sheets.", vbCritical, "No Exceptions"
Exit Sub
End Sub
' Usage Example
Sub runDeleteSheets()
Dim SheetNames As Variant: SheetNames = Array("Home Page", "Data")
deleteSheets ThisWorkbook, SheetNames
End Sub

How to add a sheet with non-duplicate name consisting of valid characters?

My code is as below:
Sub NewWorksheetTest()
Dim wsname As String
wsname = InputBox("Enter a name for the new worksheet")
On Error GoTo BadEntry
Sheets.Add
ActiveSheet.Name = wsname
Exit Sub
BadEntry:
MsgBox Err.Number & " :" & Err.Description, vbInformation, "There is an error...."
End Sub
My understanding is if I input a bad name (e.g. duplicate or containing ?/), there is a message explaining the reasons and at the same time the system stops a new sheet from being added.
An error msg is there but a new sheet is added.
As Tim Williams said, On Error GoTo BadEntry only works when the error appears, and sheets.add has no error so it will run normally.
This is another version you can use
vs1-no error checking
Option Compare Text
Sub NewWorksheetTest()
Dim wsname As String
wsname = InputBox("Enter a name for the new worksheet")
If Not (Checks_Sheetname (wsname)) Then Exit Sub 'check correct name
If Check_SheetExists(wsname) Then Exit Sub 'check dulicate
Sheets.Add
ActiveSheet.Name = wsname
End Sub
'https://learn.microsoft.com/en-us/office/vba/excel/concepts/workbooks-and-worksheets/name-a-worksheet-by-using-a-cell-value
Private Function Checks_Sheetname (wsname As String) As Boolean
If Len(wsname) > 31 Then Checks_Sheetname = False:exit function 'check sheetname length
Dim lst_str As Variant, item As Variant
lst_str = Array("/", "\", "[", "]", "*", "?", ":")
For Each item In lst_str
If InStr(wsname, item) > 0 Then
'...
Checks_Sheetname = False: Exit Function
End If
Next item
Checks_Sheetname = True
End Function
'https://stackoverflow.com/questions/6688131/test-or-check-if-sheet-exists
Private Function Check_SheetExists(wsname As String) As Boolean
For Each ws In Worksheets
If wsname = ws.Name Then
MsgBox ("exist")
Check_SheetExists = True
Exit Function
End If
Next ws
End Function
vs2: error checking
Sub NewWorksheetTest()
Dim wsname As String
wsname = InputBox("Enter a name for the new worksheet")
On Error GoTo BadEntry
Dim Act_wsname As String: Act_wsname = ActiveSheet.Name
ActiveSheet.Name = wsname: ActiveSheet.Name = Act_wsname 'checksyntax
Dim ws As Worksheet: Set ws = Sheets(wsname) 'check dulicate
If Not (ws Is Nothing) Then Exit Sub
Sheets.Add
ActiveSheet.Name = wsname
Exit Sub
BadEntry:
MsgBox Err.Number & " :" & Err.Description, vbInformation, "There is an error...."
End Sub
If the rename fails then you need to remove the added sheet
Sub NewWorksheetTest()
Dim wsname As String, ws As Worksheet
wsname = InputBox("Enter a name for the new worksheet")
On Error GoTo BadEntry
Set ws = Sheets.Add()
ws.Name = wsname
Exit Sub
BadEntry:
MsgBox Err.Number & " :" & Err.Description, vbInformation, "There is an error...."
If Not ws Is Nothing Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
End Sub

Speed up a VBA search in Excel 2016

I have the following(see below) "File Search Utility" macro that I have been using in Excel 2010. This macro searches through a specified folder of workbooks and returns the desired data (love this macro!).
In Excel 2010, the search (which searches 450+ files) takes about 2 minutes and displays the results AS they are found.
In Excel 2016, the search takes more than double the time, and no results are displayed until the macro has completely run through all of the files in the folder.
I am a novice to intermediate macro programmer at best (i.e. I know enough to be dangerous). Any help to tweak this code would be greatly appreciated.
Here is the Code:
Option Explicit
Public Sub SearchButton_Click()
Dim astrWorkbooks() As String
Dim strPartNumber As String
Dim strFolderPath As String
Dim vntWorkbooks As Variant
Dim j As Long
On Error GoTo ErrHandler
If Not ValidateData("PartNumber", strPartNumber) Then
MsgBox "Part number has not been entered.", vbExclamation
Exit Sub
End If
If Not ValidateData("SearchFolder", strFolderPath) Then
MsgBox "Search folder has not been entered.", vbExclamation
Exit Sub
End If
Call ClearResultsTable
If Not FolderExists(strFolderPath) Then
MsgBox "Search folder does not exist.", vbExclamation
Exit Sub
End If
vntWorkbooks = GetAllWorkbooks(strFolderPath)
If IsEmpty(vntWorkbooks) Then
MsgBox "Search folder does not contain any Excel workbooks.", vbExclamation
Exit Sub
End If
astrWorkbooks = vntWorkbooks
For j = LBound(astrWorkbooks) To UBound(astrWorkbooks)
Call SearchWorkbook(astrWorkbooks(j), strPartNumber)
Next j
MsgBox "Search has completed. Please check results table.", vbInformation
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
End Sub
Private Function FolderExists(ByRef strFolderPath As String) As Boolean
On Error GoTo ErrHandler
If Right(strFolderPath, 1) <> Application.PathSeparator Then
strFolderPath = strFolderPath & Application.PathSeparator
End If
FolderExists = (Dir(strFolderPath, vbDirectory) <> "")
Exit Function
ErrHandler:
FolderExists = False
End Function
Private Sub ClearResultsTable()
Dim tblResults As ListObject
Dim objFilter As AutoFilter
Dim rngBody As Range
Set tblResults = wksSearchUtility.ListObjects("Results")
Set objFilter = tblResults.AutoFilter
Set rngBody = tblResults.DataBodyRange
If Not objFilter Is Nothing Then
If objFilter.FilterMode Then
objFilter.ShowAllData
End If
End If
If Not rngBody Is Nothing Then
rngBody.Delete
End If
End Sub
Private Function ValidateData(ByVal strRangeName As String, ByRef strData As String) As Boolean
On Error GoTo ErrHandler
strData = UCase(Trim(wksSearchUtility.Range(strRangeName).Text))
ValidateData = (strData <> vbNullString)
Exit Function
ErrHandler:
ValidateData = False
End Function
Private Function GetAllWorkbooks(strFolderPath As String) As Variant
Dim lngWorkbookCount As Long
Dim astrWorkbooks() As String
Dim strFileName As String
Dim strFilePath As String
On Error GoTo ErrHandler
strFileName = Dir(strFolderPath & "*.xl*")
Do Until (strFileName = vbNullString)
lngWorkbookCount = lngWorkbookCount + 1
strFilePath = strFolderPath & strFileName
ReDim Preserve astrWorkbooks(1 To lngWorkbookCount)
astrWorkbooks(lngWorkbookCount) = strFilePath
strFileName = Dir()
Loop
If lngWorkbookCount > 0 Then
GetAllWorkbooks = astrWorkbooks
Else
GetAllWorkbooks = Empty
End If
Exit Function
ErrHandler:
GetAllWorkbooks = Empty
End Function
Private Sub SearchWorkbook(strFilePath As String, strPartNumber As String)
Dim sht As Worksheet
Dim wbk As Workbook
On Error GoTo ErrHandler
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set wbk = Workbooks.Open(strFilePath, False)
For Each sht In wbk.Worksheets
Call SearchWorksheet(sht, strPartNumber)
Next sht
ExitProc:
On Error Resume Next
wbk.Close False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
ErrHandler:
Resume ExitProc
End Sub
Private Sub SearchWorksheet(sht As Worksheet, strPartNumber As String)
Dim rngTableRow As Range
Dim cell As Range
On Error GoTo ErrHandler
For Each cell In Intersect(sht.Columns("B"), sht.UsedRange).Cells
If UCase(cell.Text) Like "*" & strPartNumber & "*" Then
Set rngTableRow = GetNextRow()
rngTableRow.Item(1).Value = sht.Parent.Name
rngTableRow.Item(2).Value = cell.Text
rngTableRow.Item(3).Value = cell.Offset(, -1).Value
rngTableRow.Item(4).Value = cell.Offset(, 6).Value
rngTableRow.Item(5).Value = cell.Offset(, 7).Value
rngTableRow.Item(6) = Range("I3")
End If
Next cell
Exit Sub
ErrHandler:
End Sub
Private Function GetNextRow() As Range
With wksSearchUtility.ListObjects("Results")
If .InsertRowRange Is Nothing Then
Set GetNextRow = .ListRows.Add.Range
Else
Set GetNextRow = .InsertRowRange
End If
End With
End Function
You are testing every single cell in column B, that's the performance killer. Check this post for how to do this using the find function, it will be WAY faster.
Find all matches in workbook using Excel VBA
Where the code in that answer defines loc, replace .cells with Intersect(sht.Columns("B"), sht.UsedRange)
it should read something like this:
Set Loc = Intersect(sht.Columns("B"), sht.UsedRange).Find(What:="Question?")
And obviously "Question" will become strPartNumber
Just wanted to include the solution mentioned by OP here as it is located on a different forum.
Option Explicit
Public Sub SearchButton_Click()
Dim astrWorkbooks() As String, strPartNumber As String, strFolderPath As String, vntWorkbooks As Variant
Dim j As Long, BlockSize As Long, myRng As Range, BigRng As Range, TempSht As Worksheet, i, myFormula As String, yyy As Range
Dim Drng As Range, SceRng As Range, Destn As Range, msg As String
Application.ScreenUpdating = False
On Error GoTo ErrHandler
If Not ValidateData("PartNumber", strPartNumber) Then
MsgBox "Part number has not been entered.", vbExclamation
Exit Sub
End If
If Not ValidateData("SearchFolder", strFolderPath) Then
MsgBox "Search folder has not been entered.", vbExclamation
Exit Sub
End If
Call ClearResultsTable
If Not FolderExists(strFolderPath) Then
MsgBox "Search folder does not exist.", vbExclamation
Exit Sub
End If
vntWorkbooks = GetAllWorkbooks(strFolderPath)
If IsEmpty(vntWorkbooks) Then
MsgBox "Search folder does not contain any Excel workbooks.", vbExclamation
Exit Sub
End If
Set TempSht = Sheets.Add
astrWorkbooks = vntWorkbooks
BlockSize = 37
For i = 1 To UBound(astrWorkbooks)
myFormula = "='" & strFolderPath & "[" & astrWorkbooks(i) & "]Invoice'!R2C1:R" & BlockSize + 1 & "C9"
Set myRng = TempSht.Range("B" & BlockSize * i - BlockSize + 1).Resize(BlockSize, 9)
myRng.FormulaArray = myFormula
myRng.Offset(, -1).Resize(, 1).Value = astrWorkbooks(i)
myFormula = "='" & strFolderPath & "[" & astrWorkbooks(i) & "]Invoice'!R3C9"
myRng.Columns(myRng.Columns.Count).Offset(, 1).FormulaR1C1 = myFormula
If BigRng Is Nothing Then Set BigRng = myRng Else Set BigRng = Union(BigRng, myRng)
Next i
Set BigRng = BigRng.Offset(, -1).Resize(, BigRng.Columns.Count + 2)
BigRng.Value = BigRng.Value
With TempSht
.Columns("D:H").Delete
.Columns("C:C").Cut
.Columns("B:B").Insert
BigRng.AutoFilter Field:=2, Criteria1:="=*" & strPartNumber & "*"
Set yyy = .AutoFilter.Range
If yyy.Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
Set Drng = .Range("A" & yyy.Rows.Count + 10)
yyy.Offset(1).Resize(yyy.Rows.Count - 1).Copy Drng
Set SceRng = Drng.CurrentRegion
Set Destn = GetNextRow.Resize(SceRng.Rows.Count)
Destn.Value = SceRng.Value
msg = "Search has completed. Please check results table."
Else
msg = "Search has completed. No results found"
End If
Application.DisplayAlerts = False: .Delete: Application.DisplayAlerts = True
End With
Application.ScreenUpdating = True
MsgBox msg, vbInformation
Exit Sub
ErrHandler:
Application.ScreenUpdating = True
MsgBox Err.Description, vbExclamation
End Sub
Private Function FolderExists(ByRef strFolderPath As String) As Boolean
On Error GoTo ErrHandler
If Right(strFolderPath, 1) <> Application.PathSeparator Then
strFolderPath = strFolderPath & Application.PathSeparator
End If
FolderExists = (Dir(strFolderPath, vbDirectory) <> "")
Exit Function
ErrHandler:
FolderExists = False
End Function
Private Sub ClearResultsTable()
Dim tblResults As ListObject
Dim objFilter As AutoFilter
Dim rngBody As Range
Set tblResults = wksSearchUtility.ListObjects("Results")
Set objFilter = tblResults.AutoFilter
Set rngBody = tblResults.DataBodyRange
If Not objFilter Is Nothing Then
If objFilter.FilterMode Then
objFilter.ShowAllData
End If
End If
If Not rngBody Is Nothing Then
rngBody.Delete
End If
End Sub
Private Function ValidateData(ByVal strRangeName As String, ByRef strData As String) As Boolean
On Error GoTo ErrHandler
strData = UCase(Trim(wksSearchUtility.Range(strRangeName).Text))
ValidateData = (strData <> vbNullString)
Exit Function
ErrHandler:
ValidateData = False
End Function
Private Function GetNextRow() As Range
With wksSearchUtility.ListObjects("Results")
If .InsertRowRange Is Nothing Then
Set GetNextRow = .ListRows.Add.Range
Else
Set GetNextRow = .InsertRowRange
End If
End With
End Function
Private Function GetAllWorkbooks(strFolderPath As String) As Variant
Dim lngWorkbookCount As Long
Dim astrWorkbooks() As String
Dim strFileName As String
Dim strFilePath As String
On Error GoTo ErrHandler
strFileName = Dir(strFolderPath & "*.xl*")
Do Until (strFileName = vbNullString)
lngWorkbookCount = lngWorkbookCount + 1
ReDim Preserve astrWorkbooks(1 To lngWorkbookCount)
astrWorkbooks(lngWorkbookCount) = strFileName
strFileName = Dir()
Loop
If lngWorkbookCount > 0 Then
GetAllWorkbooks = astrWorkbooks
Else
GetAllWorkbooks = Empty
End If
Exit Function
ErrHandler:
GetAllWorkbooks = Empty
End Function

loop to delete table rows through numerous worksheets based on a cell value

working on a loop to delete stock info from numerous worksheets in a workbook. Each sheet is named, "Client_ClientFirstName", and each table in each worksheet is the same as the worksheet name. here is the code ive come up with so far, any and all advice is appreciated.
Sub RemoveTickerFromAccounts()
Dim Client As Worksheet
Dim varTickerToFind As String
varTickerToFind = Worksheets("Entry").Cells(5, 1)
Dim tblSearchTable As Range
For Each Client In ActiveWorkbook.Worksheets
If InStr(1, Client.Name, "Client_", vbTextCompare) Then
'ws.Range("B30").Select
Worksheets(Client.Name).Activate
'tblSearchTable = ActiveSheet.ListObjects(1)
ActiveSheet.Range("b30").Select
If Selection.ListObject.Name = Client.Name Then
'tblSearchTable = "Table14"
'tblSearchTable = ActiveSheet.ListObjects(Client.Name).Select
For i = 1 To ActiveSheet.ListObjects(Client.Name).ListRows.Count
If ActiveSheet.ListObject.ListRows(i, 1).Value = varTickerToFind _
Then
tblSearchTable.ListRows(i).Delete
Exit For
Else
MsgBox "Unable to Find Ticker"
Exit For
End If
Next i
End If
End If
Next Client
End Sub
Tested:
Sub RemoveTickerFromAccounts()
Dim Client As Worksheet
Dim varTickerToFind As String
Dim tblSearch As ListObject
Dim bFound As Boolean, i As Long
varTickerToFind = Worksheets("Entry").Cells(5, 1).Value
For Each Client In ActiveWorkbook.Worksheets
If Client.Name Like "Client_*" Then
Set tblSearch = Client.ListObjects(1)
For i = 1 To tblSearch.ListRows.Count
If tblSearch.ListRows(i).Range.Cells(1).Value = varTickerToFind Then
tblSearch.ListRows(i).Delete
bFound = True
Exit For
End If
Next i
If Not bFound Then
MsgBox "Unable to Find Ticker '" & varTickerToFind & "'"
End If
End If
Next Client
End Sub

Resources