本文介绍了为什么下面的函数不返回任何值,而总是返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的程序,用于从名为"RandomNum"的函数获取随机数

Below is my program to get the random number from the function called 'RandomNum'

Sub Test()

Dim RandomNo As Variant

RandomNo = RandomNum(RandomNo)
Range("B6").Value = RandomNo

End Sub

下面是名为"RandomNum"的函数的代码,它用于创建8位随机字母数字文本.它总是向主函数返回一个空值

Below is the code for the function called 'RandomNum' and it is used to create a 8-digit random alpha numeric text. It always returns an empty value to the main function

Public Function RandomNum(RandomNo As Variant) As Variant

alphaNumericText = UCase("abcdefghijklmnopqrstuvwxyz0123456789")
alphaText = UCase("abcdefghijklmnopqrstuvwxyz")

RandomNo = ""
Randomize
For i = 1 To 8
    RandomNo = RandomNo & Mid$(alphaNumericText, Int(Rnd() * Len(alphaNumericText) + 1), 1)
Next

End Function

推荐答案

我将这样重写,以便函数返回随机字母数字 String ;无需尝试传递 ByRef 参数:

I would re-write like this so that the function returns the random alpha-numeric String; there's no need to try to pass a ByRef parameter:

Public Function RandomAlphaNumeric() As String
    Dim alphaNumericText As String
    alphaNumericText = UCase("abcdefghijklmnopqrstuvwxyz0123456789")

    Randomize
    For i = 1 To 8
        RandomAlphaNumeric = RandomAlphaNumeric & Mid$(alphaNumericText, Int(Rnd() * Len(alphaNumericText) + 1), 1)
    Next
End Function

Sub Test()
    Range("B6").Value = RandomAlphaNumeric
End Sub

您甚至可以添加功能以传递可选的 length 参数,而不是对 8 进行硬编码.

You could even add functionality to pass in an optional length parameter instead of hard-coding the 8.

这篇关于为什么下面的函数不返回任何值,而总是返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:36