Forum Discussion
CgXeng
Feb 07, 2025Copper Contributor
Controls a relay USB via VBA excel
Hi, I'm working on a project that uses VBA excel to control a relay USB to turn on/off. Can anyone help me? Thanks.
NikolinoDE
Feb 09, 2025Platinum Contributor
To control a USB relay using VBA in Excel it depends on the type of relay you are using. Most USB relays communicate via serial (COM port) or HID (Human Interface Device) protocols.
Look in the Device Manager and Check Ports (COM & LPT).
Identify the Relay Type
Check if your relay:
- Uses a virtual COM port (Serial communication) → Use MSComm or WScript
- Uses HID (Human Interface Device) → Requires API calls (Windows DLLs)
Communicating via Serial (COM Port)
If your relay uses a COM port, you can use MSComm (for older Excel) or WScript.Shell to send commands.
Example VBA Code for Serial Relay (COM Port), the code is not testet backup your file first.
Sub ControlRelay()
Dim WshShell As Object
Set WshShell = CreateObject("WScript.Shell")
' Send command to COM port (change COM3 to your actual port)
WshShell.Run "cmd.exe /c echo ON > COM3", 0, True
' Wait for 1 second
Application.Wait Now + TimeValue("00:00:01")
' Turn OFF the relay
WshShell.Run "cmd.exe /c echo OFF > COM3", 0, True
Set WshShell = Nothing
End SubIf your relay uses HID (not a COM port), you'll need to call Windows API functions to send USB commands. This method is more complex.
My answers are voluntary and without guarantee!
Hope this will help you.