Excel 2016 VBA运行时错误5:多用户共享文件部分PC报错求助
Excel VBA运行时错误5的修复方案
报错根源
部分用户的Application.UserName中不存在@符号,此时Instr(Application.UserName, "@")返回0,计算0-1得到负数,而Left函数的长度参数不能为负,直接触发Invalid procedure call or argument错误。
修正代码
Dim userAccount As String userAccount = Application.UserName ' 先判断用户名是否包含@符号 If InStr(userAccount, "@") > 0 Then Range("J1").Value = Left(userAccount, InStr(userAccount, "@") - 1) Else ' 无@时直接使用完整用户名 Range("J1").Value = userAccount End If
额外优化点
- 明确指定工作表:避免因当前激活工作表不同导致的赋值错误,可将
Range("J1")改为ThisWorkbook.Worksheets("目标工作表名称").Range("J1") - 网络权限确认:确保所有用户对共享驱动器上的文件拥有读写权限,排除权限问题引发的异常
内容的提问来源于stack exchange,提问作者Mina Azer
相关产品推荐
相关产品推荐

