0

What is the difference between the following two statements? I was writing a basic VB.net code which creates a new excel workbook and adds a new sheet. Both seem to be doing the same thing:

Dim oxl As Excel.Application
oxl = New Excel.Application
Dim oxl As Excel.Application
oxl = CreateObject("Excel.Application")

The only thing that I note is that the VB.net editor displays the following message when I am using NEW: "Object initialization can be simplified"

Can anyone pls help?

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Sougata
  • 319
  • 1
  • 10
  • 2
    Enable [Option Strict](https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-strict-statement) and you'll discover the difference. – Tu deschizi eu inchid Oct 22 '22 at 13:05
  • 2
    Since you are using the VBA tag: Note that VBA an vb.net are not the same. Your code is not valid as VBA code, because VBA requires use of the [Set](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/set-statement) statement for assigning an object to a variable. – GWD Oct 22 '22 at 13:11
  • The following post may be useful: https://stackoverflow.com/a/72794540/10024425 (see function "CreateExcelWorkbook"). – Tu deschizi eu inchid Oct 22 '22 at 13:12
  • https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/early-late-binding/ – Lundt Oct 22 '22 at 18:02

1 Answers1

0

In the sample code posted the early (or static) binding refers to compile time binding (you must add a COM reference for that):

Dim oxl As Excel.Application
oxl = New Excel.Application

And late (or dynamic) binding refers to runtime binding (for example when you use reflection) and doesn't require any COM references.

Dim oxl As Excel.Application
oxl = CreateObject("Excel.Application")

You can read more about early and late binding technologies in the Using early binding and late binding in Automation article.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • I do not understand why "binding" should be important here. I have shared my thoughts in the following link: https://stackoverflow.com/questions/74166770/confusion-in-creating-excel-application-object-using-vb-net-createobject-vs-new/74170413?noredirect=1#comment130973754_74170413. Could you please check my most recent comments there (u shall find it against the comments given by @Craig in the answer given by Andrew Morton) – Sougata Oct 25 '22 at 08:09
  • Here the question was about the difference between the `CreateObject` and `New`. So, I've answered it. – Eugene Astafiev Oct 25 '22 at 21:39