我正在开展一个与网站互动的辅助项目。我希望在计时器上运行...每10分钟,我希望此程序连接到该站点,并检查更新。下面的代码可以让我连接到已经在网站上的现有IE窗口......如果一个未打开,它将启动一个新的IE窗口,然后登录。
Public Sub ConnectToSite()
Dim Idx As Integer, Found As Integer
Dim shellWins As ShellWindows
Dim objIE As InternetExplorer
Dim bOpen As Boolean
Dim wb As Workbook
Set wb = ThisWorkbook
Set shellWins = New ShellWindows
bOpen = False
Idx = 0
For Each objIE In shellWins
Debug.Print objIE.LocationName
If objIE.LocationName = "Testing" Then
bOpen = True
Found = Idx
End If
Idx = Idx + 1
Next objIE
If bOpen Then
Set objIE = shellWins.Item(Found)
Else
Set objIE = New InternetExplorer
With objIE
.Visible = False
.navigate "https://justtesting.com/"
Application.Wait DateAdd("s", 3, Now)
Logon objIE
End With
End If
End Sub
我测试了这部分并且它有效。我的问题是......我应该如何将其作为一个函数,以便以后当我有其他计时器运行宏 - 或其他需要连接的子程序时 - 我不重复此代码?
我是否应该将一个不存在的指向objIE的指针传递给此函数ByRef并将其设置在里面?函数应该返回对象吗?
Public Function ConnectToSite(ByRef objIE as InternetExplorer) as Boolean
'Code from above
ConnectToSite = True 'Either way we would connect
End Function
Public Sub Main()
Dim IE As InternetExplorer
'In main sub
If ConnectToSite(IE) Then
'Do some stuff
End If
End Sub