vba 从串口读取到 Excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14792502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:55:37  来源:igfitidea点击:

Read from Serial port to Excel

vbaexcel-vbaserial-portarduinoexcel

提问by Atish

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!

我需要在 Excel 中创建一个按钮来从串口读取数据。我不能将任何额外的文件附加到 Excel 表格中。我需要将此excel文件传输到另一台计算机以读取此数据。以下是该文件的工作原理: 按 按钮选择串行端口。然后,按另一个按钮从串口读取数据到excel单元格中。有人可以告诉我怎么做吗?使用 VB 宏还是 ActiveX 宏?抱歉,这是我第一次为此使用 excel。请帮忙。同样,我不能将另一个文件附加到 Excel 工作表。谢谢!

回答by Udo Klein

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

我在德国 microcontroler.net 论坛中找到了关于这个主题的讨论:

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

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:

由于我在 Linux 上运行,我无法验证代码是否正确。无论如何,这是它的副本:

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