【发布时间】:2021-04-08 14:46:15
【问题描述】:
我正在为我的 VBA 代码而苦苦挣扎。我有两个潜艇:
- 第一个 Sub 标识并弹出 Internet Explorer 窗口,我的抓取宏将在该窗口上运行。这个 Sub (IEGetActivePage) 工作正常;
- 第二个 Sub 将执行抓取工作。这个 Sub 需要使用弹出 Internet Explorer 窗口的对象变量。
我的目标是从第一个 Sub (IEGetActivePage) 调用 VARIANT 变量 IE_Title 到下一个 Sub (TestScrape2) 并将其转换到一个 OBJECT 变量(以便 TestScrape2 中的代码工作)。
编辑:
-
SET函数似乎不起作用。我得到相同的结果:Internet Explorer 窗口弹出,但仅此而已。甚至没有用于检查变量类型的 MsgBox。
这是 IEGetActivePage 代码,带有 IE_Title 变量:
Option Explicit
Sub IEGetActivePage()
Dim marker As Variant
Dim IE_Window As Variant
Dim IE_count As Variant
Dim X As Variant
Dim IE_Title As Variant 'The web page used in this code is the following: https://fr.wikipedia.org/wiki/Visual_Basic_for_Applications
Dim IE As Variant
marker = 0
Set IE_Window = CreateObject("Shell.Application")
IE_count = IE_Window.Windows.Count
For X = 0 To (IE_count - 1)
On Error GoTo ErrorHandler
IE_Title = IE_Window.Windows(X).Document.Title
If IE_Title Like "Visual Basic for Applications — Wikipédia" Then
Set IE = Fenêtre.Windows(X)
marker = 1
Exit For
Else
End If
Next
If marker = 0 Then
MsgBox ("The Internet window cannot be found")
Else
AppActivate IE_Title 'Activates the correct Internet Explorer windows
'---Until there, the code works fine. The next step is an attempt to create a new variable out of the IE_Title variable and converting it to an object. As @Gustav suggested, I tried the SET function but I get the same result---
Dim IEObject As Object
Set IEObject = IE_Title.InternetExplorer
'---To check if the conversion worked, I inserted a MsgBox using the IsObject function below---
Dim VariableCheck As Boolean
If VariableCheck = IsObject(IEObject) Then
MsgBox (VariableCheck)
Else
End If
'---As a result, the message box does appear. No errors displayed either. And the scraping evidently did not work. The only thing that works is the Internet Explorer window activation. So there must be an issue here---
Call TestScrape2 'Calling the next Sub
End If
ErrorHandler:
If Err.Number > 0 Then 'TODO: handle specific error
Err.Clear
Resume Next
End If
End Sub
而下面的代码就是下一个Sub(TestScrape2):
Option Explicit
Sub TestScrape2()
Dim IEObject As Object
Set IEObject = New InternetExplorer
IEObject.Visible = True
Dim IEDocument As HTMLDocument
Set IEDocument = IEObject.Document
Debug.Print IEDocument.getElementbyId("firstHeading").innerText
End Sub
有什么想法吗?关于如何调用一个 Sub 中使用的变量并将其转换为另一个 Sub 中的对象变量?
希望这足够清楚
【问题讨论】:
-
如果多个 subs 处理相同的数据,我喜欢使用module-level variables。这样您就不必将每条数据作为参数传递。它还可以帮助您避免变量与对象声明的问题。
-
@Toddleson 你的意思是不要像
Dim IE_Title As Variant那样声明变量,我应该使用Public IE_Title As Variant? -
@James69 模块级意味着您在任何子或函数之外声明变量。应用程序会存储这些值,直到它关闭或重置,这意味着您可以运行一个宏,获取一个值,然后稍后在相同或不同的宏中使用该值。在您的情况下,这意味着您可以快速轻松地使用多个 sub 引用您的数据,而无需将所有内容作为参数传递。
标签: vba object variables internet-explorer type-conversion