In VBA check which excel sheet is active (currently shown) - vba

I'm looking for a method of checking if an excel sheet is currently active (currently shown).
I'm interested in a synchronous method and not in an event.

You could use set sh = ActiveSheet, or strShName = ActiveSheet.Name.
To test if sheet Xyz is active: If ActiveSheet.Name = "xyz" Then
You can also use If ActiveSheet.CodeName = "Sheet1" Then (VBE name)

Test for matching worksheet and workbook names.
Function IsActiveSheet(ByVal targetSheet As Worksheet) As Boolean
IsActiveSheet = targetSheet.Name = ActiveSheet.Name And _
targetSheet.Parent.Name = ActiveWorkbook.Name
End Function
It's a function. Place it in a module, and then call it from another procedure like this:
Sub Test()
Dim mySheetVar As Worksheet
Set mySheetVar = ActiveWorkbook.Worksheets("Sheet1")
' Here's the function call which returns TRUE or FALSE.
MsgBox IsActiveSheet(mySheetVar)
End Sub

If Sheet1 Is ActiveSheet Then
Call
ElseIf Sheet2 Is ActiveSheet Then

Related

VBA create new Worksheet if not exists

I am currently working on a VBA macro, that takes data from a Worksheet and copies it to another.
If the destination Worksheet does not exist it should create it and than write the data from my array.
Problem:
I have a function to test if the worksheet already exists.
If it is the case my macro will successfully write the data i want. But if the worksheet doesnt exist VBA is displaying the error you can see below.
In the list Workbook.Worksheets is no Sheet named like this but I get that error anyway.
Here is my relevant code:
(If something is missing for understanding the problem I can fill in the missing part in too)
Function sheetExists(sheetToFind As String) As Boolean
Dim Sheet As Worksheet
For Each Sheet In Worksheets
If sheetToFind = Sheet.Name Then
sheetExists = True
Exit Function
End If
Next Sheet
sheetExists = False
End Function
In my main Sub I used this code:
If sheetExists("SheetName") = False Then
Dim newSheet As Worksheet
With ThisWorkbook
.Sheets.Add(After:=Worksheets(Worksheets.Count)).Name = "SheetName"
End With
End If
The exact error:
1004 Cannot rename a sheet to the same name as another sheet, a reference object library, or a workbook referenced by Visual Basic
First it was executing successfully but after I deleted the sheet manually the error occurred.
Thanks for any help :)
Specify in which workbook to look at:
For Each Sheet In ThisWorkbook.Sheets
also not that it has to be Sheets and not Worksheets, because Worksheets only contains worksheets but Sheets also contains charts, etc. So we have to check these names too!
(Sheet then has to be Dim Sheet As Object)
You can make your function more flexible:
Function sheetExists(sheetToFind As String, Optional InWorkbook As Workbook) As Boolean
If InWorkbook Is Nothing Then Set InWorkbook = ThisWorkbook
Dim Sheet As Object
For Each Sheet In InWorkbook.Sheets
If sheetToFind = Sheet.Name Then
sheetExists = True
Exit Function
End If
Next Sheet
sheetExists = False
End Function
so you can call it:
sheetExists("SheetName") to use ThisWorkbook by default, or
sheetExists("SheetName", Workbooks("MyWorkbook")) to specify a specific workbook.
Alternatively you can use
Function sheetExists(sheetToFind As String, Optional InWorkbook As Workbook) As Boolean
If InWorkbook Is Nothing Then Set InWorkbook = ThisWorkbook
On Error Resume Next
sheetExists = Not InWorkbook.Sheets(sheetToFind) Is Nothing
End Function
which can be a bit faster if there are many sheets in a workbook.

I am unable to get the correct worksheet name when looping through a workbook

I am trying to collect data from multiple workbooks by checking the worksheet names.
However when i run my code to check the worksheetname(which is Raw Data), i am getting a false result. The code is returning only Sheet1 and Sheet2.
Below is the code:
Function WorksheetRAWExists(wsName As String) As Boolean
Dim ws As Worksheet
Dim ret As Boolean
ret = False
wsName = UCase(wsName)
For Each ws In ThisWorkbook.Sheets
If UCase(ws.Name) = "RAW DATA" Then
ret = True
Exit For
End If
Next
WorksheetRAWExists = ret
End Function
This happens because you loop through "ThisWorkbook" in your for-each, which always checks the worksheet collection in the workbook you're running the VBA code from.
If you're looking to loop through all sheets in all open workbooks then you could do something like so:
Sub test()
Dim wbk As Workbook, ws As Worksheet
For Each wbk In Workbooks
For Each ws In wbk.Worksheets
MsgBox ws.Name
Next ws
Next wbk
End Sub
Edit:
You could also pass the workbook name or index (or the workbook reference itself) to your function and check that specific reference in the workbook collection, in case looping through all open workbooks isn't what you want.

How to copy the sheet name to a column on the same sheet?

I am using this code:
Function wrksht() as Variant
wrksht = Application.Caller.Parent.Name
End function
I am continuously being thrown
run time error '424' object not found
I have a workbook with several sheets, each having a date on it.
I want to populate the first column on every sheet with its sheet name.
Function wrksht() as String
wrksht = ActiveSheet.Name
End function
UPDATE
Function DoIt()
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Sheets
sh.Range("A1") = sh.Name
Next
End Function
The above will work, but I have an easier solution:
=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,255)
Paste this value (it is a formula, not VBA code) into the cell you wish to populate with the sheet name, and it will magically appear.
Try this
Sub my_macro
On error resume next
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
ws.Range("A1") = ws.Name
Next
End sub

Hide excel worksheet via VBA

I have a workbook that has a number of worksheets each one with a colaborator name on it (Windows login username).
I've tried via VBA to loop through all Worksheets to match the actual Windows Logged On username with the matching Worksheet, and after the match is done, only that Worksheet is kept visible (with all the others being hiden).
I've managed to do this partially but i can only do it untill it finds the matching worksheet. For example, if the matching username is the third worksheet (in a total of ten for example) the code stops there. I want it to run through all worksheets and only then hide the non matching Worksheets.
First i have the following module:
Sub WorksheetFilter()
Dim Username As String
Dim Worksheetname As String
Worksheetname = ActiveWorkbook.ActiveSheet.Name
Username = Environ("Username")
If Worksheetname <> Username Then
ActiveSheet.Visible = False
End If
End Sub
Then, i call the previous module on the Workbook_Open() event:
Option Explicit
Dim WS As Worksheet
Private Sub Workbook_Open()
For Each WS In ActiveWorkbook.Worksheets
WorksheetFilter
Next
End Sub
Any hints on how this can be achieved?
Thanks,
VĂ­tor
Use the code below, and put it in the Workbook module under the Workbook_Open event.
Just loop through all sheets and compare each one with the username.
Option Explicit
Public Sht As Worksheet
Private Sub Workbook_Open()
For Each Sht In ThisWorkbook.Sheets
If Sht.Name = Environ("Username") Then
Sht.Visible = xlSheetVisible
Else
Sht.Visible = xlSheetHidden
' option 2: use very hidden, only able to unhide through code (unable to unhide using right-click)
'Sht.Visible = xlSheetVeryHidden
End If
Next Sht
End Sub
Please see below: chopped your code around a bit. You do not need to defien the worksheets name. This is for the module level, you can call it in the workbook open event as per usual
Option Explicit
Dim ws As Worksheet
Dim Username As String
Sub WorksheetFilter()
Username = Environ("Username")
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> Username Then
ws.Visible = False
Else
ws.Visible = True
End If
Next ws
End Sub
Please let me know how this works for you! :)

How do i select worksheet using an inputbox in vba

I am trying to select a worksheet every time when i open up a workbook using an inputbox in VBA. here is my code for opening a workbook but after i open up my workbook, how do i select a worksheet inside that workbook?
Sub button7_click()
dim wb as string
dim ss as string
wb = Application.GetOpenFilename
if wb <> "False" Then Workbooks.Open wb
End sub
Assuming "Sheet1" is the name of the sheet that you want to select...
Workbooks(wb).Sheets("Sheet1").Select
EDIT: And you can use something like this to get a variable sheet name from an InputBox. In its simplest form...
Dim Result As String
Result = InputBox("Provide a sheet name.")
Workbooks(wb).Sheets(Result).Select
...but I would add some error handling into this also to prevent errors from blanks, misspelled or invalid sheet names.
Let's say you have a "normal", blank Excel workbook with sheets "Sheet1", "Sheet2" and "Sheet3". Now, when the workbook opens, let's assume you want to activate (not select, as that's different) the sheet called "Sheet2".
In your workbook's ThisWorkbook module, add this code:
Private Sub Workbook_Open()
ActiveWorkbook.Sheets("Sheet2").Activate
End Sub
Make sure this code is pasted inside of the ThisWorkbook object and not in a Module, Form, or Sheet object.
Save and exit the workbook. When you re-open it, "Sheet2" will be the active sheet.
Here is the final code if anyone wants it.
Multiple selections are not quite possible , as the copied worksheet only copies across and increments the largest value of the range selected rather than all the cells selected individually ....
Sub CopyAndIncrement()
Dim ws As Worksheet
Dim Count As Integer
Dim Rng As Range
Dim myValue As Integer
Dim wsName As String
wsName = InputBox("Provide the EXACT sheet name you want to copy.")
'error handling loop for Worksheet name
For p = 1 To Worksheets.Count
If Worksheets(p).Name = wsName Then
exists = True
End If
Next p
If Not exists Then
While exists = False
wsName = InputBox("Sheet not found re-enter name.")
For p = 1 To Worksheets.Count
If Worksheets(p).Name = wsName Then
exists = True
End If
Next p
Wend
End If
Set Rng = Application.InputBox( _
Title:="Increment your worksheet", _
Prompt:="Select a cell(s) you want to increment", _
Type:=8)
On Error GoTo 0
If Rng Is Nothing Then Exit Sub 'Test to ensure User Did not cancel
'Set Rng = Rng.Cells(1, 1) 'Set Variable to first cell in user's input (ensuring only
'1 cell) >> commenting this can give multiple selections
myValue = InputBox("How many time do you want it to increment? Give me the number ")
Do While Count < myValue
For Each ws In Worksheets ' this loop selects the last sheet in the workbook
LastWs = ws.Name
i = ws.Range(Rng.Address).Value
If i > j Then
j = i
End If
Next
Sheets(wsName).Select
Sheets(wsName).Copy After:=Sheets(LastWs)
ActiveSheet.Range(Rng.Address).Value = j + 1
Count = Count + 1
Loop
End Sub