I spent some time searching for an answer but had no luck.
I'm trying to create a macro that will select multiple worksheets based on user input from an input box and combine it with a LIKE operator to select all the worksheets at once. Each of these sheets has a different name but all begin with a 5 digit number, 20001 for example, that I can use as a criteria for selection.
I can get this to work if I hard code the 5 digit value and select multiple sheets at once but can't get it to work with the input box value. I've tried different iterations of entering the input box value/variable but haven't had any luck.
Example Below with input box:
Public Sub SixPayTest()
Dim Bunumber As String
Dim ws As Worksheet
Bunumber = Application.InputBox("Enter BU #")
For Each ws In ActiveWorkbook.Sheets
If ws.Name Like bunumber Then ws.Select (False)
Next ws
End Sub
This Working example below will select all the worksheet I need it to but without the input box:
Public Sub SixPayTest()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
If ws.Name Like "*20001*" Then ws.Select (False)
Next ws
End Sub
You need to add wildcards for like value. For example:
If ws.Name Like "*" & bunumber & "*" Then
....
Even clearer would be to update value before like conditon.
bunumber="*" & bunumber & "*"
Also, if you want to find sheet with name starting with bnumber, do not add first star "*" to the string.
Related
I am working on a macro that will cycle through all of the sheets in the active workbook and will then clear a certain part of a particular worksheet, based on whether one of the relevant keywords is contained in the worksheet name. In each case the worksheet name will be different, but any I want to clear will contain one of the key words below.
I have set up a separate macro to clear the range of cells in each case. If the Worksheet name does not contain any of the keywords, I want the macro to move onto the next worksheet.
My ultimate aim is to be able to apply this to numerous different workbooks, as the project I am working on is split by region, with a separate Excel file per region.
The code I have been trying is below. There are no errors appearing when I run the code, the code does not seem to run either, in fact nothing at all happens!
Any guidance or advice would be greatly appreciated.
Sub Loop_Customer_Sheets()
Dim ws As Integer
Dim i As Integer
ws = ActiveWorkbook.Worksheets.Count
For i = 1 To ws
If ActiveSheet.Name Like "*ABC*" Then
Call ABCInfoClear
ElseIf ActiveSheet.Name Like "*DEF*" Then
Call DEFInfoClear
ElseIf ActiveSheet.Name Like "*GHI*" Then
Call GHIInfoClear
Else:
End If
Next i
End Sub
"Nothing at all happens" - fixing the issue with your code:
Your issue is that you are looping through the number of sheets, but you are only checking the ActiveSheet, which never changes! Replace your code with
ws = ActiveWorkbook.Worksheets.Count
For i = 1 To ws
With ActiveWorkbook.WorkSheets(i)
If .Name Like "*ABC*" Then
ABCInfoClear
ElseIf .Name Like "*DEF*" Then
DEFInfoClear
ElseIf ActiveSheet.Name Like "*GHI*" Then
GHIInfoClear
End If
End With
Next i
Note: you don't need the Call keyword, you can just call subs as presented above.
Alternative solutions
A better option than having numerous macros might be to create a generic sub like
Sub ClearRangeInSheet(rangeAddress As String, sh As WorkSheet)
Dim myRange As Range
Set myRange = sh.Range(rangeAddress)
myRange.ClearContents
' Any other cell clearing code e.g. for formatting here
End Sub
Then call in the loop
Dim wsCount as Long
wsCount = ActiveWorkbook.WorkSheets.Count
For i = 1 to wsCount
With ActiveWorkbook
If .WorkSheets(i).Name Like "*ABC*" Then
' Always pass ".WorkSheets(i)", but change the range address as needed
ClearRangeInSheet("A1:A20", .WorkSheets(i))
ElseIf ' Other worksheet name conditions ...
End If
End With
Next I
As suggested in the comments, you could ditch indexing the sheets, and just loop through the sheet objects themselves:
Dim wksht as WorkSheet
For Each wksht In ActiveWorkbook.WorkSheets
If wksht.Name Like "*ABC*" Then
' Always pass wksht but change the range address as needed
ClearRangeInSheet("A1:A20", wksht)
ElseIf ' Other worksheet name conditions ...
End If
Next wksht
I have a worksheet named "Photo Sheet" that i would like to declare in my codes.
Const myWorksheet = "Photo Sheet"
My question, if i have another sheet called "Photo Sheet (2)" is there a way to declare the variable as wildcard that would take any sheet starting with "Photo Sheet*" ?
Not quite clear what you want to do, but you can iterate over the worksheets, using the Like operator to select the ones which have the appropriate name:
Sub test()
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name Like "Photo Sheet*" Then Debug.Print ws.Name
Next ws
End Sub
This will print the names of all worksheets that begin "Photo Sheet". Of course, rather than printing their names you could e.g. put these worksheets in a collection for further processing.
There isn't if you use an equity operator for testing it, but you can do something similar with Like:
Const SHEET_NAME = "Photo Sheet*"
Sub WhateverYourThingDoes()
Dim ws As Worksheet
For Each ws in Worksheets
If ws.Name Like SHEET_NAME Then
'Your code here.
End If
Next
End Sub
You can't use a wildcard to declare a worksheet directly, so no set shtPhotos = Sheets(Worksheet & "*"). A declaration like that has to be unambiguous or it would potentially return a collection, which can't be assigned to a non-array variable.
So, no wildcards. What you can do is loop through all your worksheets and check whether the sheet's name contains whatever text you're looking for:
Sub FindPhotos()
Const csSheet As String = "Photo Sheet"
Dim shtPhotos As Worksheet
For Each shtPhotos In ActiveWorkbook.Sheets
If InStr(1, shtPhotos.Name, csSheet) <> 0 Then
'do something
End If
Next shtPhotos
End Sub
This is going to look at every worksheet in the active workbook and see if their name contains the text in the constant. This will work fine if you want to perform the same steps with every worksheet that begins "Photo Sheets"; if you only want it to perform those steps with one such sheet, you'd add an Exit For after performing your steps:
For Each shtPhotos In ActiveWorkbook.Sheets
If InStr(1, shtPhotos.Name, csSheet) <> 0 Then
'do something
Exit For
End If
Next shtPhotos
You could also look for a flag on the sheets that are found, so that only sheets that have, say, today's date in a specified cell would be processed:
For Each shtPhotos In ActiveWorkbook.Sheets
If InStr(1, shtPhotos.Name, csSheet) <> 0 AND _
shtphotos.range("A1").value = Date Then
'do something
End If
Next shtPhotos
I would like to select a worksheet in my activeworkbook and there is only one and it starts with EXP, how do i do that, I am trying something like below.
ActiveWorkbook.Worksheets("EXP*").Select
Loop and find:
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Sheets
If (sheet.Name Like "EXP*") Then
sheet.Select
Exit For
End If
Next
I have a materials register I am creating
Due to regulation when a material (each material has its own worksheet with a 3 digit random number added on the end to allow the same name multiple times) is deleted it cannot actually be deleted, so to work around this my workbook hides the sheet and using a deletion check on the summary page hides the appropriate row.
However what I am struggling with is a function to restore the sheet,
I have the code I need to do this however I cannot find any function to list hidden sheets.
This list can be put into the work book in a hidden column so I can reference it with my macro but as I said I cannot find anyway to list only sheets that are hidden.
Thanks for your help
You could add to your code that does the hiding to write the name of the sheet that it is hiding to your other hidden tab, and add the reverse to your code that unhides it.
Not sure if the below is applicable to your situation, but you could also put some code in worksheet events to capture when the sheet is being made invisible
Private Sub Worksheet_Deactivate()
If Me.Visible = xlSheetHidden Then MsgBox "I have been hidden"
End Sub
Does this help ..
' Function to be used in array formula on sheet to list hidden sheets
Public Function ListHiddenSheets()
Dim hiddenSheets As New dictionary
Dim sheet As Worksheet
For Each sheet In Worksheets
If sheet.Visible <> xlSheetVisible Then hiddenSheets.Add sheet.Name, Null
Next sheet
Dim vRes() As Variant
ReDim vRes(0 To hiddenSheets.Count, 0 To 0)
Dim idx As Integer
For idx = 0 To hiddenSheets.Count - 1
vRes(idx, 0) = hiddenSheets.keys(idx)
Next idx
ListHiddenSheets = vRes
End Function
?
Hidden sheets can be Hidden or VeryHidden, to capture these:
ub ListEm()
Dim ws As Worksheet
Dim StrHid As String
Dim strVHid As String
For Each ws In ActiveWorkbook.Worksheets
Select Case ws.Visible
Case xlSheetVisible
Case xlSheetHidden
StrHid = StrHid & ws.Name & vbNewLine
Case Else
strVHid = strVHid & ws.Name & vbNewLine
End Select
Next
If Len(StrHid) > 0 Then MsgBox StrHid, vbOKCancel, "Hidden Sheets"
If Len(strVHid) > 0 Then MsgBox strVHid, vbOKCancel, "Very Hidden Sheets"
End Sub
I have 2 different workbooks with a set of parameters, e.g. car parts number, sales prices, etc. The 2 different workbooks will always have the same car parts numbers but they are not in order. So I was thinking of using a vlookup to match the parameters on one workbook to the other related to the respective parts' numbers.
Thus, I used vlookup to perform this task. It works, but I want to implement this using a macro, so I would not need to manually do the vlookup every time. Is it possible to create such a macro given that the workbooks (file names) would be different every time?
I actually tried recording the macro and the vlookup records the parameters it needs relating to the file name.
EDIT: code from comment:
Sub Macro1()
ActiveCell.FormulaR1C1 = "=VLOOKUP('[TI_DBP_effective_06 May 2013.xls]NON SLL'!C1,'[TI_DBP_effective_06 May 2013.xls]NON SLL'!C1:C3,3,FALSE)"
Range("I1").Select Selection.AutoFill Destination:=Range("I1:I9779")
Range("I1:I9779").Select
End Sub
Try something like this. You will have to place this macro in your Personal macro workbook, so that it is available all the time, no matter what workbooks are open. It will prompt you for two files, and then open them, and should insert the formula. Let me know if it gives you any trouble since I am not able to test it right now.
NOTE: This looks up the value one column to the LEFT of the cell you select, and then looks in columns 1:3 of the other file. Modify as needed.
Sub Macro1()
Dim file1 As String
Dim file2 As String
Dim wbSource As Workbook
Dim wbLookup As Workbook
Dim startRange As Range
file1 = Application.GetOpenFilename(Title:="Select the file to update")
If Len(Dir(file1)) = 0 Then Exit Sub
file2 = Application.GetOpenFilename(Title:="Select the LOOKUP file")
If Len(Dir(file2)) = 0 Then Exit Sub
Set wbLookup = Workbooks.Open(file2)
Set wbSource = Workbooks.Open(file1)
On Error Resume Next
Set startRange = Application.InputBox("Select the first cell for the formula", "Autofill VLOOKUP", Type:=8)
On Error GoTo 0
If Not startRange Is Nothing Then
Application.Goto startRange
startRange.FormulaR1C1 = "=VLOOKUP('[" & wbSource.Name & "]NON SLL'!RC[-1],'[" & wbLookup.Name & "]NON SLL'!C1:C3,3,FALSE)"
startRange.AutoFill Destination:=startRange.End(xlDown)
End If
End Sub