【问题标题】:How to fix "value used in formula is wrong data type" error when trying to convert a range into an array?尝试将范围转换为数组时如何解决“公式中使用的值是错误的数据类型”错误?
【发布时间】:2019-05-31 00:30:13
【问题描述】:

我正在制作一个 udf 以将输入的范围转换为数组,如果成功完成,该函数将“工作”返回到单元格中。但是,它不断返回#VALUE!,并说:

“公式中使用的值属于错误的数据类型。”

Function test(rng As Range) As String

Dim Arr() As Variant
Arr = Range(rng)

test="worked"

End Function

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    使用:

    Function test(rng As Range) As String
    
        Dim Arr As Variant
        Arr = rng
    
        test = "worked"
    
    End Function
    

    【讨论】:

    • 注意:使这项工作起作用的是Range 类的隐式默认成员调用,通过Arr = rng 赋值中发生的隐式let-coercion。此代码的更明确的版本是Arr = rng.Value,其中Range.Value 被记录为在给定多单元格范围的情况下产生二维变体数组。这里的隐式代码是Arr = rng.[_Default],其中_DefaultRange 类的隐藏/未记录的默认成员。如果rng 只有 1 个单元格,Arr 将不是变量数组。
    【解决方案2】:

    正在输入此作为评论,但由于内容而将作为答案。请注意,@DisplayName 给出了适当的答案来解决您的问题。

    在您的代码中,您使用了语法不恰当的“Range()”。以下是适当范围引用的一些示例:

    Sheets("Name).Range("A1")  'Uses cell A1 on sheets Name
    Sheets("Name").Cells(1,1)  'Just like the above, calls cell A1
    
    i = 1
    Sheets("Name).Range("A" & i)  'Ampersand joins the variable i (typically used to iterate through a loop) with the column "A"
    
    Sheets("Name").Range("Cat")  'Uses a named range, where cat is predefined and is on sheets Name
    
    With Sheets("Name")
        Set rng = .Range(.Cells(1,1),.Cells(2,2)) 'Creates a range from A1 to B2... note the dots to make them use the appropriate sheet 
    End With
    rng.value = "Cat"  'Each cell in the range will have "Cat" input
    

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 2011-01-19
      相关资源
      最近更新 更多