Read from Serial port to Excel

2019-09-15 03:28发布

问题:

I need to create a button in Excel to read data in from serial port. I can't have any extra files attached to the excel sheet. I need to transfer this excel file to another computer to read this data. Here is how the file is suppose to function: Press button to select the serial port. Then, press another button to read data from serial port into the excel cell. Could someone please tell me how to do this? Use VB macro or ActiveX macro? Sorry, this is the first time i'm using excel for this. Help please. Again, I can't have another file attached to the excel sheet. Thank you!

回答1:

I found a discussion on exactly this topic in the german microcontroler.net forum here:

http://www.mikrocontroller.net/topic/64788

Since I am running on Linux I can not verify if the code is correct. Anyway, here is a copy of it:

Sub Send_and_Read()
  '--------------------------------------------------------
  cmnd$ = "Hello World"        'A string to send
  '--------------------------------------------------------
  Open "COM1" For Binary Access Read Write As #1
  cmnd$ = cmnd$ + Chr(13)      'add [CR] to command string
  Put #1, , cmnd$              'write string to interface
  '--------------------------------------------------------
  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
  '--------------------------------------------------------
  Cells(1, 1) = answer         'put response in cell("A1")
End Sub