这是我获取USB调制解调器COM端口的代码
Public Sub GetModemCommPort()
Dim MSComm1 As Object
Dim lngCommPort As Long
Dim strInput As String
Set MSComm1 = ThisWorkbook.Sheets("Sheet1").MSComm1
On Error Resume Next
With MSComm1
.RThreshold = 0
For lngCommPort = 1 To 12
CloseCommPort
.CommPort = lngCommPort
.PortOpen = True
If Err.Number = 0 Then
.Output = "AT" & vbCrLf
Do
DoEvents
If .InBufferCount > 0 Then
strInput = strInput & .Input
If InStr(1, strInput, "OK") > 0 Then
MsgBox "Modem Found: COM" & lngCommPort
Exit For
End If
Else
Exit Do
End If
Loop
Else
Err.Clear
End If
Next lngCommPort
CloseCommPort
.RThreshold = 1
End With
Set MSComm1 = Nothing
End Sub
Public Sub CloseCommPort()
Dim MSComm1 As Object
Set MSComm1 = ThisWorkbook.Sheets("Sheet1").MSComm1
With MSComm1
If .PortOpen Then
.PortOpen = False
End If
End With
Set MSComm1 = Nothing
End Sub
运行此代码时,从1开始循环执行时,每4或5次成功执行一次代码。
当我从8开始循环(这是我已经知道的调制解调器通讯端口)时,每次运行它都会成功执行,而不会出现任何问题。
成功执行(甚至每X次执行一次)意味着代码本身没有问题..所以我做错了吗?!
谢谢。