What does the keyword 'New' do in VBA?

后端 未结 2 809
傲寒
傲寒 2020-12-16 05:02

In VBA procedures we are constantly meeting the keyword New usually on instantiation of an object reference to an existing object instance. But in some inst

相关标签:
2条回答
  • 2020-12-16 05:23

    You said: "[We are] meeting the keyword New usually on instantiation of an object reference to an existing object instance". Exactly the opposite is true: New is used when something does not exist yet and you want to create it, well "new".

    You can omit the New keyword if something already exists, e.g. the Application object, ActiveWorkbook object and others in VBA, that is everything which was already opened by you when starting Excel.

    Dim ... As New ... is a shortcut for

    Dim ... As ...
    Set ... = New ...
    

    For your last question to create a new worksheet, it's done by

    Dim WS As Worksheet
    Set WS = Sheets.Add
    WS.Name = "My new worksheet"
    

    You cannot use Dim WS as New Worksheet, because Microsoft prevents you from doing so. Even if you specify New in that instruction, the object is still Nothing.

    0 讨论(0)
  • 2020-12-16 05:37

    When you Dim a variable you are specifying what data type it will hold. At the time of creation, its value is always Nothing until you initialize it. Set T = Application.Workbook(Bk) initializes the T variable to the specific instance of Application.Workbook, in this case 'Bk'.

    When you Dim fso as FileSystemObject, you are basically saying that fso will hold, at some point, a FileSystemObject; however its initial value is Nothing until you initialize it using Set fso = New FileSystemObject. The New keyword implies you're creating a new object instead of initializing the variable with an existing object as you do with Set T = Application.Workbook(Bk)

    Also note that Set fso = FileSystemObject would be invalid because it doesn't know what instance of FileSystemObject you wish to assign to it. This is why you use the New keyword to create a new instance of FileSystemObject.

    As stated before, Dim WS As Worksheet merely tells the compiler that you want variable WS to hold a Worksheet object. Since nothing else is specified, at the point of Dim, WS is set to Nothing

    Dim myClassModule As New cl_ChartEvents is equivalent to doing:

    Dim myClassModule as cl_ChartEvents
    Set myClassModule = New cl_ChartEvents
    

    ... except on one line of code instead of two. This differs from Dim WS As Worksheet in that the variable is initialized straight away, i.e. myClassModule is set to a new instance of cl_ChartEvents instead of Nothing.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题