What does the keyword 'New' do in VBA?

后端 未结 2 813
傲寒
傲寒 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.

提交回复
热议问题