1

I'm having a hard time with VBA errors on Excel, can someone help me understanding what this error means?

"VBA Object variable or With block variable not set error"

My function is supposed to check if a sheet exists, if not create the new sheet, rename it and return to the main function. The code works, but the error is always thrown..

Function GetWorksheetFromName(Name As String) As Worksheet
    Dim WS As Worksheet
    For Each WS In ThisWorkbook.Worksheets
        If StrComp(WS.Name, Name, vbTextCompare) = 0 Then
            Set GetWorksheetFromName = WS
            Exit Function
        End If
    Next WS

    With ThisWorkbook
        Set WS = Worksheets.Add(After:=Sheets(.Sheets.Count))
        WS.Name = Name
    End With

    Set GetWorksheetFromName = WS

End Function

P.S.: this might help, but I still haven't fixed my code

5
  • What isn't working? Works for me as With GetWorksheetFromName("ABC") : .Range("A1") = 123 : End With . First pass it creates the new worksheet, second pass it uses the same worksheet. Commented Mar 15, 2016 at 17:29
  • The code works, but throws-me this error Commented Mar 15, 2016 at 17:31
  • 1
    How are you calling it? Commented Mar 15, 2016 at 17:51
  • Which line throws the error ? Commented Mar 15, 2016 at 17:55
  • I just answered the question, I don't really know if I should leave the question or not, but at least the MSDN link can be usefull :/ Commented Mar 15, 2016 at 18:06

2 Answers 2

1
Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count)) 

note the added period before Sheets and Worksheets - your current code addresses the Sheets collection of the Active workbook, not ThisWorkbook.

Sign up to request clarification or add additional context in comments.

2 Comments

Still the same... even if I comment the bottom section I still get the error
I have found the issue, thank you for your time I was actually missing one Set statement when receiving the the result of the function... I'm still learning how to process this basic errors with no line numbers :|
0

The error was actually listed on the MSDN link

You attempted to use an object variable that has been set to Nothing.

Set MyObject = Nothing             ' Release the object.

MyCount = MyObject.Count       ' Make a reference to a released object.

Respecify a reference for the object variable. For example, use a new Set statement to set a new reference to the object.

Dim WS As Worksheet

Sheets("Config").Select
WS = GetWorksheetFromName(Range("B8").Value)

My error was on the last line, I was missing the SET

Set WS = GetWorksheetFromName(Range("B8").Value)

Thank you Tim Williams and Scott Craner for your quick help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.