View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Chip Pearson Chip Pearson is offline
external usenet poster
 
Posts: 7,247
Default how to declare a public workbook?

You can put the code in the Workbook_Open procedure in the ThisWorkbook code
module (it must be in ThisWorkbook, not some other module).

Private Sub Workbook_Open()
On Error Resume Next
Set myBook = Workbooks("Test.xls")
If Err.Number < 0 Then
' Test.xls not found. do something
Else
' Test.xls found. do something.
End If
End Sub

Next, declare the myBook variable in a regular code module (not in
ThisWorkbook).

Public myBook As Excel.Workbook


--
Cordially,
Chip Pearson
Microsoft Most Valuable Professional
Excel Product Group
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)



"choi4u" wrote in message
...
I'd like to declare a workbook and a worksheet before the first
procedure so that all other procedures can use them.

When I tryied to use Set Statement as "Set myBook =
Workbooks("test.xls")", I've got "invalid outside of a procedure"
error.

So, I guessed the Set statement may not work outside of a procedure
(I'm not sure). And then, I declared a string constant as "Public
Const myBook as "test.xls"" and used myBook in other procedure as
"Workbooks(myBook)", which worked fine.

However, I'd like to use something like myBook.mySheet.myRange.---,
insted of
Workbooks("myBook").Worksheets("mySheet").Range("m yRange").---,

Any recommendation?

Thanks in advance.