如果输出未被捕获,则输入类型更改 [英] Input type changes if output not captured

查看:75
本文介绍了如果输出未被捕获,则输入类型更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理根据输入类型做不同事情的功能。不幸的是,我发现输入的类型取决于是否捕获输出

I'm working on a function that does different things depending on the type of the input. Unfortunately, I've found that the type of the input depends on whether the output is captured or not.

Function what_type(x As Variant) As String
    Debug.Print TypeName(x)
    what_type = TypeName(x)
End Function

Sub range_test()
    Dim rng As Range
    Set rng = Sheets("Test").Range("F28:G28")
    what_type (rng)
    Debug.Print what_type(rng)
End Sub

运行 range_test 打印

Variant()
Range
Range

这不是我期望的。

什么是

推荐答案

在您首次致电 what_type ,您已经通过了(rng)的参数,即 rng 的值作为一个Variant数组。这导致Debug.Print显示 Variant()

In your first call of what_type, you have passed a parameter of (rng), i.e. the values of rng as a Variant array. This results in the Debug.Print displaying Variant().

在您的第二次调用 what_type ,您已经传递了一个参数 rng ,即实际的范围对象。这导致Debug.Print显示 Range ,并将其作为结果传回,然后再次调试Debug.Printed。

In your second call of what_type, you have passed a parameter of rng, i.e. the actual range object. This results in the Debug.Print displaying Range, and that being passed back as the result, which then is again Debug.Printed.

如果您的第一个通话更改为

If your first call was changed to just

what_type rng

它也将显示 Range 作为变量类型。

it, too, would display Range as the variable type.

或者如果您的第二个通话更改为

Or if your second call was changed to

Debug.Print what_type((rng))

它将显示 Variant()在函数内部和作为返回的结果。

it would display Variant() both inside the function and as the returned result.

PS使用子例程的语法调用函数总是一个坏主意。函数返回一个值(或者至少是应该),并且以某种方式处理返回的值始终是一个好主意,即对变量的赋值,或将其传递给另一个功能/子程序。

P.S. It is always a bad idea to invoke a function using the syntax for a subroutine. A function returns a value (or, at least, it should) and it is always a good idea to dispose of that returned value in some way, be that an assignment to a variable, or passing it to another function/subroutine.

这篇关于如果输出未被捕获,则输入类型更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆