Excel vba com port

VBA Serial Port routines for Microsoft Office

New for 2022 — Windows 10, Office 2019 (Excel, Word, Access)

Getting Serial (COM) Ports working as intended in VBA can be surprisingly difficult in certain usage scenarios.

New VBA routines here will help resolve these issues in Excel, Word and Access (Windows PC versions only).

Functions are straightforward to use with coding style to support infrequent VBA users and developers.

Intended to help implement ad-hoc projects for serial data acquisition or transfer.

No plug-ins, DLLs, ActiveX, licences, payments or registrations are required.

More Information
VBA Issues

The in-built VBA functions for COM Port data can suffer from the following issues :-

  1. Setting port parameters with the VBA open command may not work in some Windows versions e.g.

    Open "COM1:9600,N,8,1" For Read Access As #1
    (command line workaround known, settings can revert after reboot)

  2. Attempting to read data when there is none waiting will cause VBA to hang with a ‘not responding’ message.

    Get #1, , Read_Data_Byte

    The new functions address both of these issues, and also where data transfers take longer than the 5-6 second VBA timeout.

Background

The legacy of serial comms means that many online solution searches are now time-expired with links to defunct web sites etc.

New functions here are therefore a fresh start for 2022 and are based largely on Microsoft’s Win32 API calls and documentation.

Developed on Windows 10 (64-Bit) with a local Microsoft Office 2019 Professional (32-Bit VBA7) installation.

Tested on Office 2016 Professional (64-bit VBA7) and Office 2019 Professional (32-Bit VBA7)

COM Ports

Multiple com ports are supported, including physical hardware ports and synthetic virtual software ports.

All read and write functions are synchronous, in part because not all serial port types support overlapped operation.

Performance on a modern PC is good, with software timing delays required to allow the relatively slow serial com ports to catch up.

Reading, Writing and Waiting are ‘timesliced’ to ensure that VBA remains responsive during any extended data transfers or waiting times.

Debugging

  • Debugging can be set on/off per port with results shown in the VBA immediate window.

  • Extensive debug functionality makes several modules quite verbose.

Other Versions

  • No-Debug (more compact)

  • Simplified (single com port)

  • Minimal (single com port, no settings)

  • VBA6 / 32-Bit (legacy Windows/Office)

Alternatives (Excel Only)

  • Microsoft Data Streamer for Excel

Optional steps for Excel only

  • Functions can be used directly in Worksheet cells as formulas where appropriate.
  • Remove comment mark before Option Private Module to prevent function names appearing in cell formula drop-down lists.
  • Remove comment mark before Application.Volatile where indicated to refresh results when functions are used in cells and the worksheet is recalculated (e.g. with F9 key).

Optional Ribbon Customisation

Office 2010 XML and SERIAL_PORT_RIBBON example files are available in the Ribbon folder.

Function List

COM Port Control

Read/Write/Check Data

Port Signalling Functions

Show Functions

Private functions are not intended to be called directly by users.

Содержание

  1. Technical Articles
  2. Wednesday, May 19, 2010
  3. Serial Port Communication in Excel (VBA)
  4. Introduction to Serial Port Communication in VBA
  5. Serial Port Communication Script
  6. Using ActiveXperts Serial Port Component with VBA (Visual Basic for Applications)
  7. Step 1: Download and install the ActiveXperts Serial Port Component
  8. Step 2: Create a new Excel document
  9. Step 3: Fill in the dropdown-menu’s
  10. Step 4: Send an AT command to a connected Hayes compatible modem
  11. Omron Host Link Protocol Part 2 – VBA Excel

Technical Articles

This blog has been created to provide you with latest, updated and best in quality Technical Articles. Your Comments and Feedback is highly appreciated.

Wednesday, May 19, 2010

Serial Port Communication in Excel (VBA)

Introduction to Serial Port Communication in VBA

The purpose of this article is to demonstrate how you can perform serial port communication in the VBA (Visual Basic Applications — script editor included in any typical Microsoft Excel distribution) but without using the MSComm control or any other third party add-on or ActiveX. The great advantage of this method, which uses API functions to call the serial port directly, is that you do not really need to install anything on your PC, apart from the Excel itself (which, let’s admit it, already exists on most PCs). Other methods always require the installation of an ActiveX, or at least the registration of an “.ocx” file, like for instance the MSComm control. Even the method of programming in C#, which I have suggested in a different article (Serial Port Communication in C#) needs the installation of the .NET Framework and of the C# compiler itself. It is assumed that the reader would have some basic knowledge of programming (but really basic, not even intermediate)

In order to get access to the VBA script editor, you first need to make the corresponding buttons available on the Excel toolbars (they are not there by default). Once you have started your Excel, choose from the top menu: View -> Toolbars -> Visual Basic. This will make visible another small toolbar, with the following buttons:

These buttons will enable you to launch the editor in which you will be able to write the Visual Basic Code and will also allow you to directly create windows-style controls like textboxes, push buttons, labels, radio buttons, checkboxes etc. In order to make these
available on the main toolbar, you need to activate the Control Toolbox button, from the small toolbar activated at the previous step. This will, in turn, make available a number of new other buttons that will allow you to build the mentioned controls:

As a goal for this article, I would intend to demonstrate how you open the serial port, how you write a few bytes, how you read some bytes, and then how you close the serial port. In order to do all these, you will need to create four windows-style buttons, each of them performing one of the tasks that I have enumerated before.

Click on the Command Button control from the recently activated toolbar, and then draw 4 similar buttons anywhere on the surface of your excel worksheet (it will be a challenge to draw them all of the same size!):

Once you did that, click on the Visual Basic Editor button from the toolbar that you activated in the very first place.

This will open the environment in which you can write the code for the Visual Basic scripts that will perform the operations you wanted. Once there, make sure that you double click on the Sheet1(Sheet1) entry in the top left project tree window:

The effect of this action will be the opening in the main window of this environment of the actual sheet in which you will write the VB code. Once you reached this stage, copy paste the code below in there. This Visual Basic Code “defines” the constants, structures and
API functions that you will use later to perform the intended operations. The comments in the code are self explanatory.The article continues after the end of this code, please scroll all the way down.

Serial Port Communication Script

I know the code looks lengthy and elaborate, but you need not to worry about that. It actually implements many more functions than you really need to use. Some of them, for instance, are used to set high/low the control lines of the serial port (DTR, RTS) or to read the state of the other control lines (CTS, DSR). The actual functions to write/read the serial port, which are defined above too, do call some of the other functions defined, but this is not important for the end user of the code. And if you made it so far…you have half of the job done!

Make sure you save the file (by clicking the common “Save” button) and then go back to the excel worksheet, where the 4 buttons that you have drawin are waiting for you to do something with them!

First of all, make sure that the “Design Mode” button is activated in the second toolbar that you added throughout this process:

Now you can give appropriate names to each of the four buttons you have created before. In order to do this, right-click on the first of these buttons, and from the pop-up menu, choose the
Properties option:

A window will open with all the properties of the button object. Change the Caption property to “Initialise”, and then close the window. This will change the label on the first button to this very text:

Once you do this for the first button, repeat the operation and change the labels on the other three buttons
to “Write”, “Read” and “Close”.

Now it is time to start adding code to your buttons. In order to do this, click on the first button you created, and from the pop-up menu, choose theView Code option:

This will open again the scripting environment, adding a new function to the code; it will mark the
beginning of the function:

This is the place where you will write the code to initialize the serial port. For this, we will be using the CommOpen function, defined above, which takes as parameters the ID of the COM port you want to open (COM1, COM2 etc) and a few strings that define the baud rate, the parity and the number of data and stop bits. The code for realizing this is:

It opens COM1, at a baud rate of 9600, no parity, 8 data bits and one stop bit. The number of the COM port is specified by the value assigned to the intPortID variable. The lngStatus variable will contain the value returned by the CommOpen function, and will indicate if the port was successfully open or if any error was encountered.

Once you completed this function, go back to the excel sheet, and by the same process of right-clicking and choosing the View Code option, create the function for the second button, the one with the “Write” label written on it. The code for this function should be as follows:

This actually calls the CommWrite function, which takes two parameters: the number of the COM port to write to (it has to be the same like for the one you have opened with the previous CommOpen function) and a string of characters that will be sent to the serial port. In this case, theintPortID variable specifies that we deal with COM1, and the data to be sent is stored in the strData variable (the string looks funny because it is a command string for a programmable power supply we have in the lab; it basically interrogates the power supply regarding its unique identification number)

Again, the lngStatus variable will indicate if the write was successful, or if
an error occurred.

In the same way, create and add the code for the third button:

This will try to read 10 characters from COM1 and store them in the strData variable. Once the data is stored you can do whatever you want with it: put it in a table, write it in a cell from the sheet put it through another VB algorithm etc.

The next logical step is to close the serial port, for this, you should use the fourth button you have created previously in order to create the function:

Remember that the VBA in Excel is rather an interpreter than a compiler. What this means is that once you have written the code, you do not need to compile it, you just need to execute the scripts. In order to do this, make sure the “Design Mode” button is now inactive in the second toolbar that you added throughout this process:

Once this is achieved, you may go ahead and click on the buttons that you have created; each time you press a button, the code from the corresponding function will be executed. You should obviously click the buttons in the order we have discussed. First initialize the port, and then write something to the port. If you have a device connected to the serial port of your PC, then you might attempt to read 10 characters from it, if not, then just go ahead and close the port.

Please bear in mind that I did not write this code myself. It is freely available on the internet if you have the time and patience to dig it up (well, hopefully we brought it closer to you by this article). I am not a professional programmer myself, so I cannot theoretically explain every detail of the code. However, I did make a test excel file and I successfully tested it by communicating with a TTI programmable power supply.

In my opinion, this serial port communication method has some advantages: there is no need to install anything on your PC, and sometimes, the data you read from the serial port is meant to be integrated in tables or graphs (very easy to do this in excel). The trade-offs are, however, present: no real compiler, so slow execution speed, and no…ease of programming like in C#, for instance.

In Download section, you may find a file that should have resulted from thoroughly following the steps in this article.

Источник

Using ActiveXperts Serial Port Component with VBA (Visual Basic for Applications)

ActiveXperts Serial Port Component is a software development kit (SDK) that enables the user to communicate to a device over a serial interface.

Such a device can be: a weight indicator, a modem, a scanner, or any other device that is equiped with a serial port. It can even be another PC, connected via a NULL modem cable.

ActiveXperts Serial Port Component features the following:

  • Direct COM port support (like ‘COM1’)
  • TAPI (Windows Telephony Device) support (like ‘Standard 56000 bps Modem’);
  • Support for RS-232/RS422/RS485, up to 256 simultaneous ports;
  • Support for all types of Hayes compatible modems;
  • Support for serial cable as well as USB cable or Bluetooth connections;
  • Support for Virtual COM ports (i.e. COM ports redirected through the network);
  • Hardware flow control (RTS/CTS, DTR/DSR) and software flowcontrol (XON/XOFF) support;
  • Configurable baudrate/parity/stopbits, full buffered data transfer, text/binary data transfer.

Step 1: Download and install the ActiveXperts Serial Port Component

Download the ActiveXperts Serial Port Component from the ActiveXperts Download Site and start the installation. The installation guides you through the installation process.

Step 2: Create a new Excel document

Create the form displayed in the image below. To create the buttons, textarea’s and drop down menu’s, click «View», «Toolbars», «Control toolbox».

(Click on the picture to enlarge)

Wen you’re finished setting up the form, you need to fill in the dropdown menu’s. You need to load the content of your submenu when you open your workbook.You can do this using a visual basic code. To edit your visual basic code you need to be in design mode. To get in design mode, click the button «Design mode» on the control toolbox. You can edit the visual basic code behind your form in Excel by clicking the button «View code» below «Design mode» on the control toolbox.

(Click on the picture to enlarge)

Type the following code in private sub workbook_open():

Make sure you’re directing to the right sheet (worksheets(«sheet1»)).

Step 4: Send an AT command to a connected Hayes compatible modem

In this step the code to send and recieve information from the modem will be written. Type the code below down to sheet1. Make sure the buttons, comboboxes and textarea’s have the right names.

The following code shows how to query a modem:

Источник

Omron Host Link Protocol Part 2 – VBA Excel

We will use VBA in Excel to communicate to an Omron PLC. This will use the serial host link protocol.

ACC Omron Host Link VBA

In Part 1, we used VB6 to communicate from the computer to the PLC (Host Link Protocol). We will now use Visual Basic for Applications (VBA) to accomplish the same task. NETComm will be the serial driver, and Excel will be our program. Using Excel, we will have access to the Excel Object Model to utilize worksheets, ranges, etc.

Please refer to Part 1 (How to Implement the Omron PLC Host Link Protocol) for the details of the wiring of the serial port and protocol sequence.

Register Serial Communication for VBA

The first step in using VBA is to download and register NETComm.ocx. To use serial communications with VBA, you must register the NETComm.ocx driver.

Call up a dos prompt with administrator authority. (Right-click on the cmd.exe program and select run as administrator.)

Type ‘regsvr32 netcomm.ocx’

An information box indicates that the NETComm.ocx was registered successfully.

Create the Excel spreadsheet

Now open Excel and make the following on Sheet 1.

Select Developer and then Visual Basic.

If you do not have the Developer option to select, then do the following:
Select File : Options: Customized Ribbon
Select Developer and hit OK

VBA – Visual Basic for Applications will open

Insert a user form.

Excel VBA add Serial Communication.

Add NETComm1 to UserForm1. If it is not on your Toolbar, select additional controls and NETCommOCX.NETComm. Press the OK. Then drag this control onto your form.

Create three command buttons. This can be done by going to Design Mode, and under the Insert menu, you can select Command Buttons.

Here is the entire code for the application:

Note: The Chart on Sheet1 is just a selection of the first ten DM areas and inserts a bar graph.

Run the Excel Program to communicate to the Omron PLC (Host Link Protocol)

Running the program produces the following information:

Download the excel file ACC Omron Host Link VBA.XLS. This is the complete program mentioned above.

When you open the file, it will warn you about macros. This is the VBA application. Press’ Enable Macros’.

When changing the parameters on the screen, you will also get a warning about Active X. This is the NETComm.ocx that was registered above. Press ‘OK’ to run the application.

Watch on YouTube: How to Implement the Omron Host Link Protocol Part 2 – VBA

If you have any questions or need further information, please get in touch with me.
Thank you,
Garry

If you’re like most of my readers, you’re committed to learning about technology. Numbering systems used in PLCs are not challenging to learn and understand. We will walk through the numbering systems used in PLCs. This includes Bits, Decimals, Hexadecimal, ASCII, and Floating Points.

To get this free article, subscribe to my free email newsletter.

Use the information to inform other people how numbering systems work. Sign up now.

The ‘Robust Data Logging for Free’ eBook is also available as a free download. The link is included when you subscribe to ACC Automation.

Источник

Serial Port Communication in Excel (VBA)

2 November, 2015

29.507

Views3 Comments

Maurizio @ dev.emcelettronica.com discuss how we can do serial communication in Excel environment. He writes:

The purpose of this article is to demonstrate how you can perform serial port communication in the VBA (Visual Basic Applications – script editor included in any typical Microsoft Excel distribution) but without using the MSComm control or any other third party add-on or ActiveX.

Serial Port Communication in Excel (VBA) – [Link]

Please follow and like us:

fb-share-icon

Tweet

Pin Share

socialicon

Mike is the founder and editor of Electronics-Lab.com, an electronics engineering community/news and project sharing platform. He studied Electronics and Physics and enjoys everything that has moving electrons and fun. His interests lying on solar cells, microcontrollers and switchmode power supplies. Feel free to reach him for feedback, random tips or just to say hello :-)

view all posts by admin

Join 97,426 other subscribers

TagCloud

The purpose of this article is to demonstrate how you can perform serial port communication in the VBA (Visual Basic Applications – script editor included in any typical Microsoft Excel distribution) but without using the MSComm control or any other third party add-on or ActiveX.

Serial Port Communication in Excel (VBA)

1. Introduction

The great advantage of this method, which uses API functions to call the serial port directly, is that you do not really need to install anything on your PC, apart from the Excel itself (which, let’s admit it, already exists on most PCs). Other methods always require the installation of an ActiveX, or at least the registration of an “.ocx” file, like for instance the MSComm control.   In order to get access to the VBA script editor, you first need to make the corresponding buttons available on the Excel toolbars (they are not there by default). These buttons will enable you to launch the editor in which you will be able to write the Visual Basic Code and will also allow you to directly create windows-style controls like textboxes, push buttons, labels, radio buttons, checkboxes etc. In order to make these available on the main toolbar, you need to activate the Control Toolbox button, from the small toolbar activated at the previous step. As a goal for this article, I would intend to demonstrate how you open the serial port, how you write a few bytes, how you read some bytes, and then how you close the serial port. In order to do all these, you will need to create four windows-style buttons, each of them performing one of the tasks that I have enumerated before. Click on the Command Button control from the recently activated toolbar, and then draw 4 similar buttons anywhere on the surface of your excel worksheet (figure 1).

Figure 1: Command button for a version of excel

Once you did that, click on the Visual Basic Editor button from the toolbar that you activated in the very first place. This will open the environment in which you can write the code for the Visual Basic scripts that will perform the operations you wanted. Once there, make sure that you double click on the Sheet1(Sheet1) entry. The effect of this action will be the opening in the main window of this environment of the actual sheet in which you will write the VB code. Once you reached this stage, copy paste the code below in there. This Visual Basic Code “defines” the constants, structures and API functions that you will use later to perform the intended operations. The comments in the code are self

Source :  Serial Port Communication in Excel (VBA)

  • Remove From My Forums
  • Question

  • Question, I have a need to send a text string «Measure» to a device on com1 baud(4800,7,E,2) and capture the response into cell A1. Then pause for 3 seconds, and repeat for a total of 10 times. Each time populating the next empty row. A1,A2,A3,A4?

    Is this possible? Thank you


    heads up

Answers

  • Hi texastwostep,

    You need to create a SerialPort object in the VBA code, then use the write method to write the string into the COM port. Try it:

    How to: Send Strings to Serial Ports in Visual Basic

    Step by step example found in this article, this may help you a lot:

    Serial Port Communication in Excel (VBA)


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Marked as answer by

      Wednesday, April 16, 2014 12:16 PM

Понравилась статья? Поделить с друзьями:
  • Excel vba columns value
  • Excel vba cells font color
  • Excel vba columns numbers
  • Excel vba cells find if not found
  • Excel vba column from range