question about worksheet & worksheets when declare variable

abdelfattah

Well-known Member
Joined
May 3, 2019
Messages
1,429
Office Version
  1. 2019
  2. 2010
Platform
  1. Windows
hi, experts

I have dilemma I design code to copy data from userform to sheet based on sheet name first when I declare the variables wk1,wk2 as worksheets it gives me error mismatch in this line
Code:
Set wk2 = Sheets("NEW"

this is a part of code

VBA Code:
Dim lr1, lr2 As Integer

Dim wk1, wk2 As Worksheets

Set wk1 = Sheets("expirity")

Set wk2 = Sheets("NEW")

and when I change declaring worksheets to worksheet the code works , why?
I appreciate if anybody help me to understand what's the problem
 

Excel Facts

Can Excel fill bagel flavors?
You can teach Excel a new custom list. Type the list in cells, File, Options, Advanced, Edit Custom Lists, Import, OK
WorkSheets is the WorkSheet collection, it is not a data type.

Btw
VBA Code:
Dim wk1, wk2 As Worksheet
is declaring wk1 as Variant. It should be
VBA Code:
Dim wk1 As Worksheet, wk2 As Worksheet
 
Upvote 0
so I'm wrong as far I understand when use many sheets 1,2,3 ...etc it should use worksheets when declarer variables if I'm wrong , when used it so?
 
Upvote 0
When you declare a variable you are declaring it's data type not how many objects (in this case Worksheets) there are.

Each worksheet is an object, if there are are more than one then together they are a collection of worksheets.
You would use WorkSheets for example when you want to loop through the collection i.e. something like...

VBA Code:
Dim ws as WorkSheet
For each ws in WorkSheets
  MsgBox ws.name
Next
 
Upvote 0
Solution

Forum statistics

Threads
1,215,219
Messages
6,123,681
Members
449,116
Latest member
HypnoFant

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top