Forum Discussion

CgXeng's avatar
CgXeng
Copper Contributor
Feb 07, 2025

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's avatar
    NikolinoDE
    Gold 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 Sub

    If 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.

Resources