Windows 11下含宏Excel无法打开串口通信,求解决方案
解决Windows 11下Excel VBA串口通信失败的问题
针对你遇到的旧VBA串口代码在Windows 11无法运行的问题,提供以下几个可行的解决方案:
1. 检查端口权限与编号
- 先通过设备管理器确认目标串口的实际编号:打开设备管理器→展开“端口(COM和LPT)”,查看对应设备的COM端口号,避免代码中使用了错误的端口值。
- 以管理员身份运行Excel:Windows 11的UAC权限管控更严格,普通权限下VBA可能无法获取串口访问权限,右键Excel图标选择「以管理员身份运行」后再测试代码。
2. 替换旧的串口访问方式
你当前使用的Open语句属于较老旧的串口访问方法,在Windows 11兼容性较差,推荐两种更可靠的方案:
方案A:使用MSComm控件
- 打开Excel VBA编辑器(Alt+F11),点击「工具」→「附加控件」,勾选「Microsoft Comm Control 6.0 (SP6)」并确定。
- 在窗体或模块中使用以下代码示例:
Dim comm As MSComm Set comm = New MSComm With comm .CommPort = port ' 替换为实际端口号,比如3 .Settings = "19200,N,8,1" .PortOpen = True ' 打开串口 ' 发送指令示例 .Output = "你的指令内容" & vbCrLf ' 关闭串口 .PortOpen = False End With Set comm = Nothing
方案B:使用Windows API(无需额外控件)
直接调用Windows系统API实现串口访问,兼容性更好:
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long Private Declare Function SetCommState Lib "kernel32" (ByVal hFile As Long, lpDCB As DCB) As Long Private Declare Function WriteFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, lpOverlapped As Long) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Type DCB DCBlength As Long BaudRate As Long fBinary As Integer fParity As Integer fOutxCtsFlow As Integer fOutxDsrFlow As Integer fDtrControl As Integer fDsrSensitivity As Integer fTXContinueOnXoff As Integer fOutX As Integer fInX As Integer fErrorChar As Integer fNull As Integer fRtsControl As Integer fAbortOnError As Integer fDummy2 As Integer wReserved As Integer XonLim As Integer XoffLim As Integer ByteSize As Byte Parity As Byte StopBits As Byte XonChar As Byte XoffChar As Byte ErrorChar As Byte EofChar As Byte EvtChar As Byte wReserved1 As Integer End Type Sub SerialSend() Dim hCom As Long Dim dcb As DCB Dim bytesWritten As Long Dim port As Integer: port = 3 ' 替换为实际端口号 ' 打开串口 hCom = CreateFile("COM" & port, &HC0000000, 0, 0, 3, 0, 0) If hCom = -1 Then MsgBox "无法打开串口" Exit Sub End If ' 配置串口参数 dcb.DCBlength = Len(dcb) dcb.BaudRate = 19200 dcb.ByteSize = 8 dcb.Parity = 0 ' N=0, O=1, E=2, M=3, S=4 dcb.StopBits = 0 ' 1位停止位=0, 1.5=1, 2=2 SetCommState hCom, dcb ' 发送数据 WriteFile hCom, "测试指令" & vbCrLf, Len("测试指令" & vbCrLf), bytesWritten, 0 ' 关闭串口 CloseHandle hCom End Sub
3. 调整Excel宏安全设置
- 打开Excel,点击「文件」→「选项」→「信任中心」→「信任中心设置」→「宏设置」,选择「启用所有宏(不推荐;可能会运行有潜在危险的代码)」(或仅信任该文件所在的文件夹,添加到信任位置)。
- 确保文件未被标记为“来自互联网”:右键Excel文件→「属性」→勾选「解除锁定」(如果有该选项)。
内容的提问来源于stack exchange,提问作者Pradeep Kumar Sharma




