“Compile error: the variable has not been defined” using call function
“Compile error: the variable has not been defined” using call function
我有一个打开网页的宏,分配某些变量,然后使用 Call
函数调用另一个过程。我需要在第二个过程中使用第一个过程中定义的一些变量(例如 numberOfPages
),但出现以下错误:
Compile error: the variable has not been defined
谁能告诉我错误是什么以及如何解决?我在下面详细介绍了这两个过程。
Sub test()
Dim element As IHTMLElement
Dim elements As IHTMLElementCollection
Dim ie As InternetExplorer
Dim numberOfPages As Double
Dim html As HTMLDocument
Set ie = New InternetExplorer
ie.Visible = True
ie.navigate "https://cebra.com.ar/category/73/Juego-de-Construccion.html"
Do While ie.readyState <> READYSTATE_COMPLETE
Application.StatusBar = "Loading Web page …"
DoEvents
Loop
Set html = ie.document
Set elements = html.getElementsByClassName("container")
Set ElementCol = html.getElementsByTagName("a")
numberOfPages = ie.document.querySelectorAll(".setPage").Length
'MsgBox numberOfPages
For Each ele In ie.document.getElementsByTagName("li")
For Each element In elements
If element.className = "container" Then
'Do something
Call procedure
End If
Next element
Next
MsgBox "Done"
End Sub
Option Explicit
Public Sub procedure()
MsgBox numberOfPages
'I want to use the internet explorer opened and this variable to do something
End Sub
正如@Karlomanio 所说,您需要将变量传递给您的 sub-procedure(请不要将其称为 "procedure")。
这是您的代码,经过调整后可以使 numberOfPages
正常工作:
Option Explicit
Public Sub WebProcedure(numberOfPages as Long)
MsgBox numberOfPages
'Do something here based on the number of pages
End Sub
这将在您的 test()
子中使用以下行来调用:
WebProcedure numberOfPages
我有一个打开网页的宏,分配某些变量,然后使用 Call
函数调用另一个过程。我需要在第二个过程中使用第一个过程中定义的一些变量(例如 numberOfPages
),但出现以下错误:
Compile error: the variable has not been defined
谁能告诉我错误是什么以及如何解决?我在下面详细介绍了这两个过程。
Sub test()
Dim element As IHTMLElement
Dim elements As IHTMLElementCollection
Dim ie As InternetExplorer
Dim numberOfPages As Double
Dim html As HTMLDocument
Set ie = New InternetExplorer
ie.Visible = True
ie.navigate "https://cebra.com.ar/category/73/Juego-de-Construccion.html"
Do While ie.readyState <> READYSTATE_COMPLETE
Application.StatusBar = "Loading Web page …"
DoEvents
Loop
Set html = ie.document
Set elements = html.getElementsByClassName("container")
Set ElementCol = html.getElementsByTagName("a")
numberOfPages = ie.document.querySelectorAll(".setPage").Length
'MsgBox numberOfPages
For Each ele In ie.document.getElementsByTagName("li")
For Each element In elements
If element.className = "container" Then
'Do something
Call procedure
End If
Next element
Next
MsgBox "Done"
End Sub
Option Explicit
Public Sub procedure()
MsgBox numberOfPages
'I want to use the internet explorer opened and this variable to do something
End Sub
正如@Karlomanio 所说,您需要将变量传递给您的 sub-procedure(请不要将其称为 "procedure")。
这是您的代码,经过调整后可以使 numberOfPages
正常工作:
Option Explicit
Public Sub WebProcedure(numberOfPages as Long)
MsgBox numberOfPages
'Do something here based on the number of pages
End Sub
这将在您的 test()
子中使用以下行来调用:
WebProcedure numberOfPages