Workbook.getWorksheet("Name") does not work (only pulls up active worksheet)

Pal, Amrita 0 Reputation points
2023-07-05T18:16:12.76+00:00

Hi! In my script I'm using Workbook.getWorksheet("Name") to access a specific sheet that I want my code to access. However, if I'm clicked on a different sheet, .getWorksheet() does not access the sheet by name and instead accesses whatever sheet I'm currently clicked on (so it essentially works like .getActiveWorksheet()). Does anyone know why this would be happening? Thanks!

Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
2,088 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tanay Prasad 2,140 Reputation points
    2023-07-07T06:43:06.69+00:00

    Hi Amrita,

    The getWorksheet() method returns a worksheet object based on its name or index, but when it is used, it takes into account the active sheet in the workbook. The method will not return the sheet you intended to access by name, but the one you are currently clicked on.

    You can use the 'Worksheets' collection and iterate through the sheets to find the one with the required name, ensuring that you always retrieve the right sheet.

    Here's an example-

    Dim ws As Worksheet
    Dim targetSheetName As String
    targetSheetName = "Sheet1" ' Replace with the name of your desired sheet
    
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = targetSheetName Then
            ' Found the desired sheet
            ' Your code here to work with the sheet (ws)
            Exit For ' Exit the loop since we found the sheet
        End If
    Next ws
    
    

    Best Regards.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.