Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Worksheets & Worksheet obj

Tags:

excel

vba

I'm trying to understand the difference between worksheets & worksheet obj in Excel VBA. I understand from the MSDN reference that the worksheet is a child obj of worksheets & sheets.

However, we reference every worksheet using the worksheets obj, not the worksheet obj. e.g.

worksheets("ExcelIsCool").range("a1").value -> CORRECT
worksheet ("ExcelIsCool").range("a1").value -> INCORRECT

My question is whats the difference between the two?

Is worksheet only used for declaring a variable (the only place where I've used so far). e.g.

dim wks as worksheet 
like image 509
Kayote Avatar asked Sep 03 '15 08:09

Kayote


1 Answers

Like @Orphid has already stated, Worksheets is a collection of Worksheet objects.

When declaring a Worksheet variable, you can explicitly declare it as such.

Dim ws As Worksheet
Set ws = Worksheets("Sheet1")

So you're declaring a Worksheet from the Collection of Worksheets.

You can also loop through each Worksheet within a Collection.

Dim ws As Worksheet

For Each ws In Worksheets
    Debug.Print ws.Name
Next ws

So you can see that Worksheet is used in scenarios where you're explicitly referring to a single Worksheet, primarily when declaring a variable.

like image 132
luke_t Avatar answered Oct 03 '22 15:10

luke_t