VBA串口通信

VBA Serial Port Communication

我的任务是打开、写入、读取响应,然后关闭 com 端口。所以顺序

我使用的是 32 位 win OS 并且我尝试了几种不同的方法-

https://gist.github.com/heiswayi/f47dfd8dc38955322bef

涉及集成 win32.dll,我无法弄清楚如何在 VBA excel

中调用 win32

What is the best way to access a serial port from VBA?

这只是导致 excel 每次我尝试修改和 运行 代码时崩溃...再次不确定这是否与睡眠功能有关。

我发现的另一件事是一堆 SDK 是我预算库中用于 VBA 串行通信的成本方式。

类似于Read from Serial port to Excel 我修改它来回答这个问题。

Private Sub CommandButton1_Click()
Open "COM1:9600,N,8,1,X" For Binary Access Read Write As #1   'Opens Com Port with Baud rate and bit settings
 Cmnd = "#AddressReading" + Chr(13)    'Message assembled to be sent to device on serial port
 Put #1, , Cmnd                'Sends assembled message
  answer = ""                  'clear response string
  char = Input(1, #1)          'get first character
  While (char <> Chr(13))      'loop until [CR]
    If (char > Chr(31)) Then
      answer = answer + char   'add, if printable char
    Else
      ' Do what ever you like
    End If
    char = Input(1, #1)        'get the next character
  Wend
  Close #1
 Range("C2").Value = answer    'places response in desired cell
End Sub