1

Could someone explain me why when exactly one is written windows property of workbook in the code below.

I found in a book this listing, its aim is to count all visible workbooks and i do not understand why one is written in brackets. Thank you in advance.

Public Function lCountVisibleWorkbooks() As Long

    Dim lCount As Long
    Dim wkbBook As Workbook
    For Each wkbBook In Application.Workbooks
        If wkbBook.Windows(1).Visible Then
            lCount = lCount + 1
        End If
    Next wkbBook
    lCountVisibleWorkbooks = lCount
End Function
Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
Oliver
  • 79
  • 1
  • 8

2 Answers2

3

You can use the New Window Ribbon button (in the View tab), to create additional windows for a workbook:

New Window

Book1 has 4 windows

If a workbook has 4 opened windows, its Workbooks collection will contain 4 items - you can verify that in the immediate pane (Ctrl+G):

?ThisWorkbook.Windows.Count
 4

Your code-taken-in-a-book has a bug: it doesn't return the number of visible workbooks as it claims. Rather, it returns the number of workbooks where window 1 is visible.

Keep the 4 windows opened, and hide the first one:

ThisWorkbook.Windows(1).Visible = False

Window1 is hidden now

It's still there, and ThisWorkbook is still visible, ...but your function will deem that workbook "invisible" because the first window is hidden.


That (1) is an index, a subscript - it's VBA's syntax for accessing the items in an array or collection.

Dim items As New Collection
items.Add "a"
items.Add "b"
items.Add "c"
Debug.Print items(1) 'prints "a"

Windows is a collection property of a Workbook object, containing Window object instances - so wkbBook.Windows(1) is accessing the first object of that collection. (MSDN)

Side note, do yourself a favor and drop that lowercase l Hungarian prefix for Long - that Hungarian notation hurts readability. Use identifier names you can pronounce, and keep functions/procedures under 10 lines, you won't need bad mnemonics to figure out what's what.

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
0

It looks to me like this is checking the first window of each workbook. It wants to check to see there are no visible workbooks before taking an action. The workbook could have multiple windows. This would only check the first one.

Daniel Humfleet
  • 509
  • 3
  • 5