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

Excel VBA函数取消注释bar = Worksheets("Communicators")后返回#Value的原因咨询

取消注释VBA语句后返回#Value错误的原因

这是因为VBA中对象类型变量赋值必须使用Set关键字,你取消注释的代码里漏掉了它:

  • bar是Worksheet类型的对象变量,直接用bar = Worksheets("Communicators")是错误写法,VBA会尝试把Worksheets("Communicators")的默认属性(即工作表名称,字符串类型)赋值给对象变量bar,类型不匹配直接触发运行时错误,导致函数返回#Value。
  • 而你直接用Worksheets("Communicators").Name是直接访问对象的属性,没有涉及对象变量赋值,所以不会报错。

另外要注意,foo是Range对象变量,赋值时同样需要Set关键字,否则也会触发相同错误。修正后的代码如下:

Function concatRng(rng As Range) As String
     Dim c As Range
     Dim foo As Range
     Dim bar As Worksheet
     Set bar = Worksheets("Communicators") ' 加上Set关键字
     Set foo = bar.Range("A3:O3") ' Range对象赋值同样需要Set
     concatRng = bar.Name & "|" & rng.Columns.Count
     For Each c In rng
          concatRng = concatRng & " - " & c.Value
     Next
     concatRng = concatRng & "|"
End Function

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:45:42