gpt4 book ai didi

vba - VBA 中的后期绑定(bind)与早期绑定(bind)——(CreateObject() 与 New)

转载 作者:行者123 更新时间:2023-12-01 13:19:48 26 4
gpt4 key购买 nike

我正在尝试使用 VBA 代码来调用需要使用 OAuth2 进行身份验证的 protected API。一旦我尝试打开一个 URL,我就会被重定向到 ADFS 页面进行身份验证,然后我会回来。

现在对于某些使用 CreateObject("InternetExplorer.Application").Navigate URL 的应用程序可以正常工作,对于其他网络应用程序我需要使用 New InternetExplorerMedium 以使代码正常工作。

您能告诉我这些对象之间的区别吗?为什么有些网站使用一个对象而有些网站使用另一个对象?

谢谢

最佳答案

这种引用对象的方式称为“早期”和“后期绑定(bind)”。 From MSDN :

The Visual Basic compiler performs a process called binding when an object is assigned to an object variable.

An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.

By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.

You should use early-bound objects whenever possible, because they allow the compiler to make important optimizations that yield more efficient applications. Early-bound objects are significantly faster than late-bound objects and make your code easier to read and maintain by stating exactly what kind of objects are being used.

TL DR:

不同之处在于,在早期绑定(bind)中,您可以获得智能感知和编译时间奖励,但您应该确保 你已经添加了相应的库。


  • 后期绑定(bind)的用法示例:

Sub MyLateBinding()

Dim objExcelApp As Object
Dim strName As String

'Definition of variables and assigning object:
strName = "somename"
Set objExcelApp = GetObject(, "Excel.Application")

'A Is Nothing check:
If objExcelApp Is Nothing Then Set objExcelApp = CreateObject("Excel.Application")

'Doing something with the Excel Object
objExcelApp.Caption = strName

MsgBox strName

End Sub

  • 早期绑定(bind)的用法示例:

首先确保从 VBE>Extras>Libraries 添加 MS Excel 16.0 Object Library:

enter image description here


Sub MyEarlyBinding()

Dim objExcelApp As New Excel.Application
Dim strName As String

'Definition of variables and assigning object:
strName = "somename"

'A IsNothing check:
If objExcelApp Is Nothing Then Set objExcelApp = CreateObject("Excel.Application")

'Doing something with the Excel Object
objExcelApp.Caption = strName

MsgBox strName

End Sub

相关文章:

关于vba - VBA 中的后期绑定(bind)与早期绑定(bind)——(CreateObject() 与 New),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50583705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com