Excel VBA函数返回Attachment对象时提示对象变量未设置错误
VBA函数返回对象时报"Object variable or With block variable not set"解决
问题现象
自定义VBA函数GetAttachmentById用于按指定Id遍历文件夹匹配对应附件,返回自定义Attachment类型对象,代码运行到最后返回值行时抛出错误:
Object variable or With block variable not set
调试确认函数内newAttachment对象已正常实例化,代码中未使用With块,无法定位错误根因。
相关实现代码如下:
Function GetAttachmentById(Id As String) As Attachment Dim newAttachment As Attachment Set newAttachment = New Attachment Dim Directory As String Directory = "C:\Users\user\Desktop\VBA" Dim fso, newFile, folder, Files Set fso = CreateObject("Scripting.FileSystemObject") Set folder = fso.GetFolder(Directory) Set Files = folder.Files For Each file In Files If InStr(file.Name, Id) > 0 Then newAttachment.Id = Id newAttachment.AttachmentName = file.Name newAttachment.AttachmentPath = file.Path End If Next file GetAttachmentById = newAttachment
错误根因
VBA语法中,所有对象类型的赋值操作(包括给函数返回值赋值)必须使用Set关键字,值类型(数字、字符串、布尔值等)赋值才可以直接用=。
最后一行写的GetAttachmentById = newAttachment是值类型的赋值语法,解释器会尝试读取newAttachment的默认属性值做值拷贝,而不是传递对象引用;如果Attachment类没有定义默认属性,就会触发对象变量未设置的报错,和newAttachment是否实例化、是否使用With块无关。
另外贴出的代码末尾缺失End Function结束标记,运行时会直接触发编译错误,也需要补全。
修复方法
- 把最后一行返回对象的语句前加上
Set关键字:
Set GetAttachmentById = newAttachment
- 在函数末尾补上
End Function标记。
可选优化点
- 匹配到符合条件的文件后直接加
Exit For退出循环,不需要遍历完文件夹内所有文件,提升执行效率 - 给所有变量增加显式类型声明,比如
Dim fso As Object, file As Object,避免隐式Variant类型带来的非预期问题 - 增加未找到匹配文件的分支判断,避免返回的
Attachment对象属性为空导致后续调用出错 - 移除未使用的
newFile变量声明,保持代码整洁
内容的提问来源于stack exchange,提问作者Dobi Tamás
相关产品推荐
相关产品推荐

