本帖最后由 Java_Devil 于 2012-12-31 14:49:25 编辑

解决方案 »

  1.   

    Option Explicit
    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)Private Sub Command4_Click()
        Dim saveTimer As Single
        Dim flag As Integer
        Dim sj(0 To 1) As Byte
        Dim strBuff As String
        Dim sErr As String
        
        sj(0) = &H1
        sj(1) = &H4
        Text1.Text = "begin"
        Dim i As Long
        
        On Error GoTo ErrHandler
        For i = 0 To 5
            saveTimer = Timer
            
            With MSComm1
                .CommPort = i
                .Settings = "9600,n,8,1"
                .InputLen = 0
                .PortOpen = True
                .Output = sj
                
                While Timer < saveTimer + 2
                    DoEvents
                    Sleep 100
                    If .InBufferCount > 0 Then
                        Text1 = Text1 & vbCrLf & .Input
                        Exit For
                    Else
                        Text2.Text = Text2 & vbCrLf & CStr(i) + "不是匹配的端口,没有数据返回"
                        .PortOpen = False
                    End If
                Wend
            End With
    NextPort:
        Next i
        
        Exit Sub
    ErrHandler:
        Text2.Text = Text2.Text & vbCrLf & CStr(i) & Err.Description
        Resume NextPort
    End Sub
      

  2.   

    这样会好点:Private Sub Command4_Click()
        Dim saveTimer As Single
        Dim flag As Integer
        Dim sj(0 To 1) As Byte
        Dim strBuff As String
        Dim sErr As String
        
        sj(0) = &H1
        sj(1) = &H4
        Text1.Text = "begin"
        Dim i As Long
        
        On Error GoTo ErrHandler
        For i = 0 To 5
            saveTimer = Timer
            
            With MSComm1
                .CommPort = i
                .Settings = "9600,n,8,1"
                .InputLen = 0
                .PortOpen = True
                .Output = sj
                
                While Timer < saveTimer + 2
                    DoEvents
                    Sleep 100
                    If .InBufferCount > 0 Then
                        Text1 = Text1 & vbCrLf & .Input
                        Exit For
                    End If
                Wend
                
                Text2.Text = Text2 & vbCrLf & CStr(i) + "不是匹配的端口,没有数据返回"
                .PortOpen = False
            End With
    NextPort:
        Next i
        
        Exit Sub
    ErrHandler:
        Text2.Text = Text2.Text & vbCrLf & CStr(i) & Err.Description
        Resume NextPort
    End Sub