Translate

2018年10月3日 星期三

Excel VBA 尋找可用的RS232 port

參考:VB如何得知可用的RS232 Port?

VBA 新增表單並新增一個CommandButtor1、ComboBox1

程式碼如下:

 
Private Sub CommandButton1_Click()
    End
End Sub

Private Sub UserForm_Initialize()
    Dim i As Byte
    For i = 1 To 9
        If IsComPortAvailable(i) = True Then
            ComboBox1.AddItem i
        End If
    Next
End Sub
Function IsComPortAvailable(ByVal portNum As Integer) As Boolean
    Dim fnum As Integer
    On Error Resume Next
    fnum = FreeFile
    Open "COM" & CStr(portNum) For Binary Shared As #fnum
    If Err = 0 Then
        Close #fnum
        IsComPortAvailable = True
    End If
End Function

執行畫面:



沒有留言:

張貼留言