1

I have a strange problem defining a class in an Excel VBA macro.

To do this I go to Excel→DEVELOPER(tab)→Visual Basic (the new view is opened). In this new view I do Project Name→Insert→Class Module and a new file is created.

Then I try to create a simple class in this file, like:

Class VirtualWindow    
Public Sub Class_Initialize()
    Debug.Print "Class_Initialize"
End Sub

Public Sub Class_Terminate()
    Debug.Print "Class_Terminate"
End Sub
End Class

End Class is in red color, this meaning that it's not ok and when I try running it to see what error it throws it gives me the "Invalid outside procedure" error. I don't understand where is the problem.

Community
  • 1
  • 1
Lucian
  • 874
  • 11
  • 33

2 Answers2

1

You don't need the Class VirtualWindow and End Class here (since it is Visual Basic for Applications, not Visual Basic 6: VB vs. VBA) you can define the name in the properties field:

enter image description here

After this, from another function or class you can create an instance of the class:

Private w as VirtualWindow

Public Sub YourSub()
   Set w = new VirtualWindow
End Sub
Community
  • 1
  • 1
agold
  • 6,140
  • 9
  • 38
  • 54
1

You're mixing up VB6 syntax with another language I think. You do not have to put "Class VirtualWindow" and "End Class" in your code. Just:

Public Sub Class_Initialize()
    Debug.Print "Class_Initialize"
End Sub

Public Sub Class_Terminate()
    Debug.Print "Class_Terminate"
End Sub
Wouter
  • 383
  • 1
  • 12