Type mismatch error VBA loop through worksheets - vba

I keep getting a type mismatch error and have tried changing the type a few times. I'm just trying to loop through each worksheet and a specified range to see if that word exists in every cell of that range.
Sub CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Dim strCheck As Range
Set arrVar = ActiveWorkbook.Worksheets
'MsgBox (arrVar)
For Each ws In arrVar
If ws.Range("C9:G20").Value = "Word" Then
MsgBox (True)
End If
Next ws
End Sub

When you have a range with many columns, it creates an array.
Taking the array into consideration like so:
Sub CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Dim strCheck As Range
Set arrVar = ActiveWorkbook.Worksheets
'MsgBox (arrVar)
For Each ws In arrVar
For each col in ws.Range("C9:G20").Cells
if col.Value = "Word" Then
MsgBox (True)
end if
End If
Next ws
End Sub

You can't get the value of ws.Range("C9:G20") and compare it to one string. You've selected multiple cells. If you want to return True when nay one of these cells contains "Word" or when all of them contain "Word" you'll need to iterate over them.
This is an example of how to return whether or not your range contains "Word" anywhere at least once
Function CheckWord()
Dim arrVar As Variant
Dim ws As Worksheet
Set arrVar = ActiveWorkbook.Worksheets
For Each ws In arrVar
Dim c
For Each c In ws.Range("C9:G20").Cells
If c = "Word" Then
CheckWord = True
Exit Function
End If
Next c
Next ws
End Function

Sub CheckWord()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If Not ws.Range("C9:G20").Find(What:="Word", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False) Is Nothing Then MsgBox "Found in " & ws.Name
Next ws
End Sub

Related

Deleting specific sheets and those which do not meet a criteria

I have a macro where I create a number of sheets that take their names from the values in column c, cell 7 onwards in a sheet called "Schedule". I am using the following code for that
Sub CreateDataSheets()
'Updateby Extendoffice 20161215
Dim xRg As Variant
Dim wSh As Excel.Worksheet
Dim wBk As Excel.Workbook
Set wSh = ActiveSheet
Set wBk = ActiveWorkbook
Application.ScreenUpdating = False
For Each xRg In wSh.Range("C7", Range("C7").End(xlDown))
If Not IsError(xRg) Then
If xRg <> "" Then
If Not WorksheetExists((xRg)) Then
With wBk
.Sheets.Add after:=.Sheets(.Sheets.Count), Type:="L:\London\General\Reference & Tools\Software\BIM\IiA_Specifications\Excel\Uk Specification Template.xltx"
ActiveSheet.Name = xRg.Value
End With
End If
End If
End If
Next xRg
Application.ScreenUpdating = True
End Sub
Now I need another Macro where if I change or delete any of these values in Column C, I want to create new updated ones and delete all the sheets that are redundant. While doing this, I want to retain the sheets called Schedule, Home and CoverSheet. Below is the code I tried to write but that would not work.
Sub DeleteNewSheets()
Dim ws As Worksheet
Dim ArrayOne() As Variant
Dim wsName As Variant
Dim Matched As Boolean
Dim DirArray As Variant
DirArray = Range("C7:C11")
ArrayOne = Array("Home", "Schedule", "CoverSheet", DirArray.Value)
Application.DisplayAlerts = False
For Each ws In Sheets
Matched = False
For Each wsName In ArrayOne
If wsName = ws.Name Then
Matched = True
Exit For
End If
Next
If Not Matched Then
ws.Delete
End If
Next ws
Application.DisplayAlerts = True
End Sub
Would really appreciate any ideas...
DirArray is beeing created as a Variant and the position 4 of your Array ArrayOne is actually another array and not a string.
To fix it, initialize the ArrayOne just like this:
ArrayOne = Array("Home", "Schedule", "CoverSheet")
Dim Name As Variant
For Each Name In DirArray
If Name <> "" Then
ReDim Preserve ArrayOne(UBound(ArrayOne) + 1)
ArrayOne(UBound(ArrayOne)) = Name
End If
Next
It will also not consider empty values on the range you selected.
Consider changing your removing steps as on Sam's answer
Iterating over a changing set is often a bad idea. Do something like this instead
For i = Sheets.Count to 1 Step -1
If ....
Sheets(i).Delete
End If
Next i

Counting cells of worksheets within another workbook

I have one xlsm file with a single button in it which, when clicked, is supposed to open a separate workbook and search through all contained worksheets for cells of a specific colour.
The problem is, instead of searching the other workbook's worksheets, it just searches itself. I'm new to VBA, and feel like i've been round the internet 6 times trying to solve this. What am I doing wrong here?
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim holdCount As Integer
Dim cellColour As Long
Dim cell As Range, rng As Range
Set wb = Workbooks.Open("blahblahblah.xls")
Set rng = Range("A1:A20")
holdCount = 0
cellColour = RGB(255, 153, 0)
For Each ws In wb.Worksheets
For Each cell In rng
If cell.Interior.Color = cellColour Then
holdCount = holdCount + 1
End If
Next cell
Next ws
MsgBox "found " & holdCount
End Sub
It looks to me like you aren't fully qualifying your Range
Move this inside of your ws loop instead of where it is now.
Set rng = ws.Range("A1:A20")
BraX pointed out that I needed to qualify the Range WITHIN the For Each ws loop, so here is the fixed and working code. Again, all credit to Brax.
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim holdCount As Integer
Dim cellColour As Long
Dim cell As Range, rng As Range
Set wb = Workbooks.Open("blahblahblah.xls")
holdCount = 0
cellColour = RGB(255, 153, 0)
For Each ws In wb.Worksheets
With ws
Set rng = ws.Range("A1:A20")
For Each cell In rng
If cell.Interior.Color = cellColour Then
holdCount = holdCount + 1
End If
Next cell
End With
Next ws
MsgBox "found " & holdCount
End Sub

Looping through different sheets

I would appreciate your help with the macro I am trying to create.
I have an xls file with a bunch of worksheets, some of which named "1", "2", "3", and so forth. I would like to create a macro that loops only through those 'number-named' worksheets, hence NOT according to the index as in the code below. (Sheet "1" is not the first sheet in the workbook). Before the loop I need to define both the cell range and sheets.
Below is my (wrong) attempt.
Sub Refresh ()
Dim i As Integer
Dim rng As Range
Set rng = Range("A10:TZ180")
For i = 1 To 30
Sheets(i).Activate
rng.Select
rng.ClearContents
Application.Run macro:="xxx"
Next i
End Sub
dim w as worksheet
for each w in activeworkbook.worksheets
if isnumeric(w.name) then
w.range("A10:TZ180").clearcontents
xxx()
end if
next
If the macro "xxx()" requires a selected range you just need to add a select statement. (Borrowing from GSerg)
Dim w As Worksheet
For Each w In ActiveWorkbook.Worksheets
If IsNumeric(w.Name) Then
w.Range("A10:TZ180").ClearContents
w.Range("A10:TZ180").Select
Application.Run macro:="xxx"
End If
Next
To clear up your misunderstanding about assigning a range see the following:
Sub Refresh()
Dim ws As Worksheet
Dim rng As Range
Dim i As Integer
For Each ws In ActiveWorkbook.Worksheets
If IsNumeric(ws.Name) Then
'you must activate the worksheet before selecting a range on it
ws.Activate
'note the qualifier: ws.range()
Set rng = ws.Range("A10:TZ180")
'since the range is on the active sheet, we can select it
rng.Select
rng.ClearContents
Application.Run macro:="xxx"
End If
Next
End Sub
Sub test2()
Dim ws As Worksheet
Dim rg As Range
Dim arrSheets As Variant
arrSheets = Array("Sheet1", "Sheet2", "Sheet3")
Dim x As Long
For x = LBound(arrSheets) To UBound(arrSheets)
Set ws = Worksheets(arrSheets(x))
ws.Activate
'...
Next
End Sub
Sub test3()
Dim ws As Worksheet
Dim x As Long
For x = 1 To 20
Set ws = Worksheets(CStr(x))
ws.Activate
'...
Next
End Sub
try this
Sub main()
Dim shtNames As Variant, shtName As Variant
shtNames = Array(1, 2, 3, 4) '<== put your actual sheets "number name"
For Each shtName In shtNames
With Worksheets(CStr(shtName))
.Range("A10:TZ180").ClearContents
.Range("A10:TZ180").Select
Application.Run macro:="MacroToRun"
End With
Next shtName
End Sub
Sub MacroToRun()
MsgBox "hello from cells '" & Selection.Address & "' in sheet '" & ActiveCell.Parent.Name & "'"
End Sub

How can I set a worksheet object based on a worksheet's codename?

The worksheet name may change. Because of that I want to set the worksheet object based on the worksheet's codename. How can I do this?
My best attempt so far is:
Sub UpdateNameDropdown()
Dim wksName As String
wksName = ThisWorkbook.Sheets(Sheet16).Name
Dim wks As Worksheet
Set wks = Sheets(wksName)
End Sub
But I get a type mismatch error on the row wksName = ThisWorkbook.Sheets.Sheet16.Name
This?
Sub Sample()
Dim wks As Worksheet
Set wks = Sheet16
With wks
Debug.Print .Name
'~~> Do what you want
End With
End Sub
This uses the codename as a String
Sub CodeIt()
Dim CodeName As String
CodeName = "Sheet1"
Dim WS As Worksheet, GetWorksheetFromCodeName As Worksheet
For Each WS In ThisWorkbook.Worksheets
If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then
Set GetWorksheetFromCodeName = WS
Exit For
End If
Next WS
MsgBox GetWorksheetFromCodeName.Name
End Sub
Thank you Gary's Student. I midified your function to the following:
Function GetWorksheetFromCodename(codeName As String) As Worksheet
Dim wks As Worksheet
For Each wks In ThisWorkbook.Worksheets
If StrComp(wks.codeName, codeName, vbTextCompare) = 0 Then
Set GetWorksheetFromCodename = wks
Exit For
End If
Next wks
End Function

Excel VBA loop & cell value match

What I am trying to do seems basic enough, however I don't know where I am going wrong with the code.
I want to run the selected cell through a loop of the worksheets and select the worksheet that matches the selected cell located in cell B1.
Dim SelectedCell as Range
Dim ws As Worksheet
Set SelectedCell = Range(ActiveCell.Address)
For Each ws In ActiveWorkbook.Worksheets
If ws.Range("B1").Value = SelectedCell.Value Then
ActiveSheet.Select
End If
Next ws
End Sub
Thanks in advance for all the help!
Try instead
Dim ws As Worksheet
SelectedCell = ActiveCell
For Each ws In ActiveWorkbook.Worksheets
If ws.cells(1,2) = SelectedCell Then
ws.Select
End If
Next ws
End Sub
Select cell run macro will select the sheet name that matches the selected cell. (Case sensitive)
Dim SelectCell As String
Dim ws As Worksheet
SelectCell = ActiveCell.Value2
For Each ws In ActiveWorkbook.Worksheets
If ws.Name = SelectCell Then
ws.Select
End ID
Next ws