You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA中从函数获取Scripting.Dictionary遇参数错误,求解决方案

VBA函数返回Scripting.Dictionary对象的正确写法

你的代码存在几个关键问题,导致出现Wrong number of arguments or invalid property assignment错误:

  • 函数DicCreation内的dic变量未声明,也未创建Scripting.Dictionary实例,相当于返回一个未定义的对象
  • 返回对象类型时必须使用Set关键字赋值,直接DicCreation = dic是错误的语法
  • VBA完全支持直接将函数返回类型设为Scripting.Dictionary或Object,无需用Variant

下面是两种可行的解决方案:

方案一:早绑定(带代码提示)

先在VBA编辑器中添加引用:点击「工具」→「引用」,勾选「Microsoft Scripting Runtime」。之后可以直接使用Scripting.Dictionary类型,编写代码时有智能提示:

Dim dic As Scripting.Dictionary
Set dic = DicCreation()

Function DicCreation() As Scripting.Dictionary
    ' 创建Dictionary实例
    Dim tempDic As New Scripting.Dictionary
    ' 可在此添加键值对,示例:
    ' tempDic.Add "Name", "张三"
    ' tempDic.Add "Age", 25
    
    ' 用Set返回对象
    Set DicCreation = tempDic
End Function

方案二:晚绑定(无需引用,兼容性更强)

如果不需要代码提示,或者要保证代码在未添加引用的电脑上也能运行,用晚绑定方式:

Dim dic As Object
Set dic = DicCreation()

Function DicCreation() As Object
    ' 创建Dictionary实例
    Dim tempDic As Object
    Set tempDic = CreateObject("Scripting.Dictionary")
    ' 可在此添加键值对,示例:
    ' tempDic.Add "Name", "李四"
    ' tempDic.Add "Age", 30
    
    ' 用Set返回对象
    Set DicCreation = tempDic
End Function

核心要点:

  • 必须在函数内部先创建Scripting.Dictionary的实例
  • 返回对象类型时,一定要用Set关键字给函数返回值赋值

内容的提问来源于stack exchange,提问作者Nocxy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:22:15