pass worksheet as parameter and then utilize that parameter as a variable

Why am I receiving an object required error for aSheet_Recon (MAIN) There is a sheet titled MAIN. I did not declare somesheet anywhere else.

Sub aSheet_Recon(somesheet As Worksheet)
...
End Sub
Sub tester()
aSheet_Recon (MAIN)
End Sub

Update from answers and new challenge

How do I then utilize the worksheet parameter as a variable through the rest of the procedure. I receive a type mismatch error when variable cA attempts to reference the value MAIN which is the passed worksheet paramter.

Sub aSheet_Recon(sheetname As Worksheet) cName = "Fund ID" cA = Sheets(sheetname).Rows.Find(What:=UCase(cName), LookAt:=xlWhole, SearchDirection:=xlNext).Column
End Sub
1

3 Answers

You have to do this:

Sub tester() dim ws as worksheet 'Creating a worksheet variable to pass set ws = Sheets("MAIN") 'Assigning the sheet you want to pass to this variable aSheet_Recon(ws) 'Sending the newly created WorkSheet variable containing your worksheet
End sub

aSheet_Recon needs a WorkSheet argument, and will not work unless that's exactly what you're sending it (not a worksheet's Name, codename, index, etc. But the worksheet itself).

EDIT:

In answer to your own edit, here is how to use the worksheet you receive as an argument:

Sub aSheet_Recon(sheetname As Worksheet) cName = "Fund ID" cA = sheetname.Rows.Find(What:=UCase(cName), LookAt:=xlWhole, SearchDirection:=xlNext).Column
End Sub

You can also write it like:

sheetname.Range("A1") = "Hello!"

As a matter of fact, 'sheetname' is considered like a Worksheet in itself, and NOT a sheet's name. For the sheet's name, you would write sheetname.Name:

msgbox sheetname.Name

Will return "MAIN"

Because of this, I suggest changing "sheetname" to "MySheet" or something less confusing.

2

Sheets are not global objects (How would a sheet called "Dim" or "500 x Beef Supreme" be handled?); you need to fetch the Sheet from the Sheets collection:

aSheet_Recon Sheets("MAIN")
0

What worked for me is to use the ActiveSheet method. Something like this...

Sub tester() Worksheets("MAIN").Activate aSheet_Recon
End Sub
Sub aSheet_Recon() 'MsgBox(ActiveSheet.Name) cName = "Fund ID" cA = ActiveSheet.Rows.Find(What:=UCase(cName)).Column
End Sub

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like