检查是否有活动的互联网连接

发布于 2024-07-13 07:17:40 字数 575 浏览 6 评论 0原文

编写了一个小应用程序,可以访问大量搜索网站并将结果放入 Word 文档中,该应用程序每天运行数百次。

它将各个搜索结果保存在多个本地文件夹中,以便下次搜索这些单词时,它会在本地获取它们,而不是再次加载网站。

这工作得很好——尽管它并不快。 人们印象深刻,因为直到几周前,他们通过手动加载六个不同的搜索网站,进行搜索,然后将结果复制并粘贴到 Word 文档中来手动完成此操作。

然而我们办公室的网络不太稳定,最近半天就断线了。 这意味着大约 400 个错误搜索已保存在本地文件夹中,并插入到最终文档中。

当一个人进行搜索时,他们可以判断互联网是否中断,然后他们就会进行搜索。 但显然,这个应用程序无法判断,并且因为我没有使用 API 或任何东西,并且因为我仅限于使用 VBA 环境(我什至不允许使用 MZ 工具),所以我需要找到某种方法来在继续程序流程之前检查互联网是否正常工作,不要依赖太多参考,最好不要对短语“404 Page Not Found”进行屏幕抓取。

我对 VB 不太熟悉,而且 VBA 在很多方面都在毁掉我,所以可能有一些简单的方法可以做到这一点,这就是我在这里问的原因。

感谢任何帮助。

Wrote a small app that accesses a bunch of search websites and puts the results in a word document, which gets run a few hundred times a day.

It saves individual search results in a number of local folders so the next time those words are searched, it grabs them locally instead of loading the website again.

This works fine - even though it's not quick. People are impressed because until a few weeks ago they did this manually by literally loading up six different search websites, searching, and then copying and pasting the results in a word document.

However, our Office's internet is unreliable, and has been down the last half a day. This has meant about 400 bad searches have been saved in the local folders, and inserted into the final documents.

When a person was searching they could tell if the internet was broken and they would do their searches later. Obviously, though, this app can't tell, and because I'm not using APIs or anything, and because I am limited to using the VBA environment (I'm not even allowed MZ tools), I need to find some way to check that the internet is working before continuing with the program flow, without relying on too many references, and preferably without screenscraping for the phrase "404 Page Not Found".

I'm not very familiar with VB, and VBA is ruining me in so many ways, so there's probably some easy way to do this, which is why I'm asking here.

Appreciate any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

自由如风 2024-07-20 07:17:41

不幸的是,由于以下几个原因,这是一个有点难以回答的问题:

  1. 如何定义不工作的互联网连接? 您检查 IP 地址是否有效? 你能ping通吗? 你怎么知道你有权限检查这些东西? 您如何知道计算机的防火墙/防病毒软件不会导致异常行为?
  2. 一旦确定连接正常工作,如果连接在操作过程中断开,您该怎么办?

可能有很多方法可以做你想做的事情,但是很多“细节决定成败”类型的事情往往会出现。 您有什么方法可以检查保存的搜索是否有效? 如果是这样,这可能是最好的方法。

Unfortunately, this is a bit of a difficult question to answer for a couple of reasons:

  1. How do you define a non-working internet connection? Do you check for a valid IP address? Do you ping out? How do you know that you have permissions to check these things? How do you know that the computer's firewall/antivirus isn't causing wonky behavior?
  2. Once you've established that the connection is working, what do you do if the connection drops mid-operation?

There are probably ways to do what you want to do, but a lot of "devil's in the details" type things tend to pop up. Do you have any way to check that the saved search is valid? If so, that would probably be the best way to do this.

小情绪 2024-07-20 07:17:41

根据 shakalpesh 的回答及其评论,(至少)有两种方法可以将网页放入 Word,而无需解析 XMLHTTP60 对象返回的 XML。

(注意,HTTP 状态代码 200 表示“请求已成功” - 请参阅 此处

  • XMLHTTP60.ResponseText 写入文本文件,然后对该文本文件调用 Documents.Open
如果 (xhr.Status = 200) 那么 
      hOutFile = 自由文件 
      打开“C:\foo.html”以输出为 #hOutFile 
      打印 #hOutFile, xhr.responseText 
      关闭#hOutFile 
  万一 

  // ... 

  文档.打开“C:\foo.html” 
  

这样做的缺点是某些链接的元素可能会丢失,并且在文件打开时您会收到一个消息框,

  • 使用 XMLHTTP60 对象检查 URL 状态,然后像以前一样使用 Documents.Open 打开 URL :
如果 (xhr.Status = 200) 那么 
      文档.打开“http://foo.bar.com/index.html” 
  万一 
  

XMLHTTP60 请求成功而 Documents.Open 请求失败(反之亦然)的可能性很小。 希望这应该是一个相当不常见的事件

Building on shakalpesh's answer and the comments to it, there are (at least) two ways to get the web page into Word without parsing the XML returned by the XMLHTTP60 object.

(NB the HTTP status code of 200 indicates that "the request has succeeded" - see here)

  • write the XMLHTTP60.ResponseText out to a text file and then call Documents.Open on that text file
If (xhr.Status = 200) Then
    hOutFile = FreeFile
    Open "C:\foo.html" For Output As #hOutFile
    Print #hOutFile, xhr.responseText
    Close #hOutFile
End If

// ...

Documents.Open "C:\foo.html"

This has the disadvantage that some linked elements may be lost and you'll get a message box when the file opens

  • check the URL status with the XMLHTTP60 object and then use Documents.Open to open the URL as before:
If (xhr.Status = 200) Then
    Documents.Open "http://foo.bar.com/index.html"
End If

There is a slight chance that the XMLHTTP60 request could succeed and the Documents.Open one fail (or vice versa). Hopefully this should be a fairly uncommon event though

俏︾媚 2024-07-20 07:17:41

我发现这里和其他地方的大多数答案令人困惑或不完整,所以这里是像我这样的傻瓜如何做的:

'paste this code in at the top of your module (it will not work elsewhere)
Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef dwflags As Long, ByVal dwReserved As Long) As Long

Private Const INTERNET_CONNECTION_MODEM As Long = &H1
Private Const INTERNET_CONNECTION_LAN As Long = &H2
Private Const INTERNET_CONNECTION_PROXY As Long = &H4
Private Const INTERNET_CONNECTION_OFFLINE As Long = &H20

'paste this code in anywhere
Function IsInternetConnected() As Boolean
    Dim L As Long
    Dim R As Long
    R = InternetGetConnectedState(L, 0&)
    If R = 0 Then
        IsInternetConnected = False
    Else
        If R <= 4 Then IsInternetConnected = True Else IsInternetConnected = False
    
    End If
End Function

'your main function/calling function would look something like this
Private Sub btnInternetFunction_Click()
    If IsInternetConnected() = True Then
        MsgBox ("You are connected to the Internet")
        'code to execute Internet-required function here
    Else
        MsgBox ("You are not connected to the Internet or there is an issue with your Internet connection.")
    End If
End Sub

I found most answers here and elsewhere confusing or incomplete, so here is how to do it for dummies like me:

'paste this code in at the top of your module (it will not work elsewhere)
Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef dwflags As Long, ByVal dwReserved As Long) As Long

Private Const INTERNET_CONNECTION_MODEM As Long = &H1
Private Const INTERNET_CONNECTION_LAN As Long = &H2
Private Const INTERNET_CONNECTION_PROXY As Long = &H4
Private Const INTERNET_CONNECTION_OFFLINE As Long = &H20

'paste this code in anywhere
Function IsInternetConnected() As Boolean
    Dim L As Long
    Dim R As Long
    R = InternetGetConnectedState(L, 0&)
    If R = 0 Then
        IsInternetConnected = False
    Else
        If R <= 4 Then IsInternetConnected = True Else IsInternetConnected = False
    
    End If
End Function

'your main function/calling function would look something like this
Private Sub btnInternetFunction_Click()
    If IsInternetConnected() = True Then
        MsgBox ("You are connected to the Internet")
        'code to execute Internet-required function here
    Else
        MsgBox ("You are not connected to the Internet or there is an issue with your Internet connection.")
    End If
End Sub
↘紸啶 2024-07-20 07:17:41

这就是我用的。 我更喜欢它,因为它不需要任何外部引用或 DLL。

Public Function IsConnected()
    Dim objFS As Object
    Dim objShell As Object
    Dim objTempFile As Object
    Dim strLine As String
    Dim strFileName As String
    Dim strHostAddress As String
    Dim strTempFolder As String

    strTempFolder = "C:\PingTemp"
    strHostAddress = "8.8.8.8"
    IsConnected = True ' Assume success
    Set objFS = CreateObject("Scripting.FileSystemObject")
    Set objShell = CreateObject("Wscript.Shell")

    If Dir(strTempFolder, vbDirectory) = "" Then
      MkDir strTempFolder
    End If

    strFileName = strTempFolder & "\" & objFS.GetTempName
    If Dir(strFileName) <> "" Then
      objFS.DeleteFile (strFileName)
    End If

    objShell.Run "cmd /c ping " & strHostAddress & " -n 1 -w 1 > " & strFileName, 0, True
    Set objTempFile = objFS.OpenTextFile(strFileName, 1)
    Do While objTempFile.AtEndOfStream <> True
        strLine = objTempFile.Readline
        If InStr(1, UCase(strLine), "REQUEST TIMED OUT.") > 0 Or InStr(1, UCase(strLine), "COULD NOT FIND HOST") > 0 Then
            IsConnected = False
        End If
    Loop
    objTempFile.Close
    objFS.DeleteFile (strFileName)
    objFS.DeleteFolder (strTempFolder)

    ' Remove this after testing.  Function will return True or False
    MsgBox IsConnected
End Function

This is what I use. I prefer it because it doesn't require any external references or DLLs.

Public Function IsConnected()
    Dim objFS As Object
    Dim objShell As Object
    Dim objTempFile As Object
    Dim strLine As String
    Dim strFileName As String
    Dim strHostAddress As String
    Dim strTempFolder As String

    strTempFolder = "C:\PingTemp"
    strHostAddress = "8.8.8.8"
    IsConnected = True ' Assume success
    Set objFS = CreateObject("Scripting.FileSystemObject")
    Set objShell = CreateObject("Wscript.Shell")

    If Dir(strTempFolder, vbDirectory) = "" Then
      MkDir strTempFolder
    End If

    strFileName = strTempFolder & "\" & objFS.GetTempName
    If Dir(strFileName) <> "" Then
      objFS.DeleteFile (strFileName)
    End If

    objShell.Run "cmd /c ping " & strHostAddress & " -n 1 -w 1 > " & strFileName, 0, True
    Set objTempFile = objFS.OpenTextFile(strFileName, 1)
    Do While objTempFile.AtEndOfStream <> True
        strLine = objTempFile.Readline
        If InStr(1, UCase(strLine), "REQUEST TIMED OUT.") > 0 Or InStr(1, UCase(strLine), "COULD NOT FIND HOST") > 0 Then
            IsConnected = False
        End If
    Loop
    objTempFile.Close
    objFS.DeleteFile (strFileName)
    objFS.DeleteFolder (strTempFolder)

    ' Remove this after testing.  Function will return True or False
    MsgBox IsConnected
End Function
和我恋爱吧 2024-07-20 07:17:41

我遇到了同样的问题,经过大量谷歌搜索后,我意识到有一种更简单的方法可以做到这一点......它要求用户启用 Microsoft Internet Explorer 控件库,但仅此而已。 这个想法是,您的代码在获取网页文档(HTML)后导航到网站(在本例中为谷歌)。 在搜索框中输入一个值。

Sub Test1()
On Error GoTo no_internet 'Error handler when no internet
Dim IE As New SHDocVw.InternetExplorer

IE.Visible = False 'Not to show the browser when it runs
IE.navigate "www.google.com" 'navigates to google

Do While IE.ReadyState <> READYSTATE_COMPLETE 'loops until it is ready
Loop

'Here It gets the element "q" from the form "f" of the HTML document of the webpage, which is the search box in google.com
'If there is connection, it will run, quit and then go to the msgbox.
'If there is no connection, there will be an error and it will go to the error handler "no_internet" that is declared on top of the code
IE.document.forms("f").elements("q").Value = "test"
IE.Quit

MsgBox "Internet Connection: YES"
Exit Sub
no_internet:
IE.Quit
MsgBox "Internet Connection: NO" ' and here it will know that there is no connection.
End Sub

I encourted this same problem and after googling a lot, I realized there was a simpler way to do it... It requires the user to enable the Microsoft Internet Explorer Controlers library, but that is all. The idea is that your code navigates to a website (in this case google), and after getting the webpage document (HTML). puts a value in the search box.

Sub Test1()
On Error GoTo no_internet 'Error handler when no internet
Dim IE As New SHDocVw.InternetExplorer

IE.Visible = False 'Not to show the browser when it runs
IE.navigate "www.google.com" 'navigates to google

Do While IE.ReadyState <> READYSTATE_COMPLETE 'loops until it is ready
Loop

'Here It gets the element "q" from the form "f" of the HTML document of the webpage, which is the search box in google.com
'If there is connection, it will run, quit and then go to the msgbox.
'If there is no connection, there will be an error and it will go to the error handler "no_internet" that is declared on top of the code
IE.document.forms("f").elements("q").Value = "test"
IE.Quit

MsgBox "Internet Connection: YES"
Exit Sub
no_internet:
IE.Quit
MsgBox "Internet Connection: NO" ' and here it will know that there is no connection.
End Sub
怀里藏娇 2024-07-20 07:17:40

显然,你的问题有很多层次。 您应该从定义“连接到互联网”开始,然后继续制定后备策略,包括在失败时不写入无效文件。

至于“我是否已连接”问题,您可以尝试利用 Win32 API:

Private Declare Function InternetGetConnectedState Lib "wininet.dll" _
(ByRef dwflags As Long, ByVal dwReserved As Long ) As Long

Public Function GetInternetConnectedState() As Boolean
  GetInternetConnectedState = InternetGetConnectedState(0&,0&)
End Function

尽管根据您的网络设置(代理/NAT/防火墙限制等),Windows 可能对此有与您不同的看法。

尝试获取您感兴趣的页面,检查 HTTP 标头中的返回状态(网关超时、404、当它“不起作用”时您期望发生的任何情况)也可能是一种方法。

Obviously, your problem has many levels. You should start by defining "connected to the internet", and go on with developing fallback strategies that include not writing invalid files on failure.

As for the "am I connected" question, you can try tapping into the Win32 API:

Private Declare Function InternetGetConnectedState Lib "wininet.dll" _
(ByRef dwflags As Long, ByVal dwReserved As Long ) As Long

Public Function GetInternetConnectedState() As Boolean
  GetInternetConnectedState = InternetGetConnectedState(0&,0&)
End Function

Though depending on your network setup (proxy/NAT/firewall restrictions etc.), Windows might have a different opinion about this than you.

Trying to GET the pages you are interested in, checking on the return status in the HTTP headers (gateway timeout, 404, whatever you expect to happen when it "doen't work) might also be a way to go.

夜巴黎 2024-07-20 07:17:40

您可以使用 MSXML 库 & 使用 XMLHttpRequest 类来检查一些事情

,例如

On Error Resume Next
Dim request As MSXML2.XMLHTTP60
request.Open "http://www.google.com"
request.Send
Msgbox request.Status

状态将为您提供请求发生情况的 HTTP 状态代码。
根据您的情况,您可能需要进行更多检查。

希望有帮助。

You could use MSXML library & use XMLHttpRequest class to check for things

e.g.

On Error Resume Next
Dim request As MSXML2.XMLHTTP60
request.Open "http://www.google.com"
request.Send
Msgbox request.Status

The status will give you HTTP Status code of what happened to the request.
You might have to do some more checks, depending on your scenario.

Hope that helps.

江城子 2024-07-20 07:17:40

使用以下代码检查互联网连接
参考文献中第一个可用的 XML v6.0

Function checkInternetConnection() As Integer
'code to check for internet connection
'by Daniel Isoje
On Error Resume Next
 checkInternetConnection = False
 Dim objSvrHTTP As ServerXMLHTTP
 Dim varProjectID, varCatID, strT As String
 Set objSvrHTTP = New ServerXMLHTTP
 objSvrHTTP.Open "GET", "http://www.google.com"
 objSvrHTTP.setRequestHeader "Accept", "application/xml"
 objSvrHTTP.setRequestHeader "Content-Type", "application/xml"
 objSvrHTTP.Send strT
 If err = 0 Then
 checkInternetConnection = True
 Else
  MsgBox "Internet connection not estableshed: " & err.Description & "", 64, "Additt !"
 End If
End Function

Use the following code to check for internet connection
first anable XML v6.0 in your references

Function checkInternetConnection() As Integer
'code to check for internet connection
'by Daniel Isoje
On Error Resume Next
 checkInternetConnection = False
 Dim objSvrHTTP As ServerXMLHTTP
 Dim varProjectID, varCatID, strT As String
 Set objSvrHTTP = New ServerXMLHTTP
 objSvrHTTP.Open "GET", "http://www.google.com"
 objSvrHTTP.setRequestHeader "Accept", "application/xml"
 objSvrHTTP.setRequestHeader "Content-Type", "application/xml"
 objSvrHTTP.Send strT
 If err = 0 Then
 checkInternetConnection = True
 Else
  MsgBox "Internet connection not estableshed: " & err.Description & "", 64, "Additt !"
 End If
End Function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文