简体   繁体   English

Excel VBA函数不适用于作为范围的参数

[英]Excel VBA Function will not work with an argument as a Range

I have written a fairly simple VBA function that I want to use in my worksheet and others that are linked to the macro worksheet. 我编写了一个相当简单的VBA函数,希望在我的工作表以及链接到宏工作表的其他函数中使用。 I am allowing the user to input a value OR a range (basically a cell reference) as the argument. 我允许用户输入一个值或一个范围(基本上是一个单元格引用)作为参数。

Public Function TSTT(arg As Range) As Single
    Dim a25 As Variant
    a25 = 522.6 - (arg / 155.2867)

    TSTT= a25
End Function

The problem is when I use Range as the type (as above) and the user inputs a value in the formula I get a #VALUE as the return. 问题是当我使用Range作为类型(如上)并且用户在公式中输入一个值时,我得到一个#VALUE作为返回值。

If I declare the argument as a single then it works if the user inputs a value or a cell reference. 如果我将参数声明为单个参数,那么如果用户输入值或单元格引用,则该参数将起作用。

Finally if I declare the argument as a Variant it also works with both types of input. 最后,如果我将参数声明为Variant,则它也适用于两种类型的输入。

To allow both types of inputs should I use the Variant or the expected type? 要允许两种类型的输入,我应该使用Variant还是期望的类型?

You don't need to declare the argument in the function header, you can test what the user has given you. 您不需要在函数头中声明参数,可以测试用户给您的内容。 You can actually test what the user has given you: 您实际上可以测试用户给您的内容:

Function foo(r) As String
    If TypeOf r Is Range Then
      v = r.Value
    Else
        v = r
    End If
    '
    '   more stuff
    '
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM