首页 > 解决方案 > 如何使用 Randomize 使我的 UDF 成为非易失性?

问题描述

我正在尝试创建一个为我创建随机 ID 的函数。

在 Excel 中使用它时,ID 列将填充: =UPPER(CONCATENATE(LEFT([@Group],4),RandomString(4)))

除非 Random String 中的长度输入 (4) 发生变化,否则我不希望公式的 Randomise 部分再次重新计算(我永远不会更改长度,因此它将是静态的)。唯一应该更改的字符是与 (LEFT([@Group],4).

现在,当我更改组列中的任何单元格时,我的 TaskID 列中的所有单元格都会重新计算,因此应用程序 volatile 并没有足够的帮助。

谢谢

Function RandomString(Length As Integer)

Application.Volatile False

Dim CharacterBank As Variant
Dim x As Long
Dim str As String

'Test Length Input
  If Length < 1 Then
    MsgBox "Length variable must be greater than 0"
    Exit Function
  End If

CharacterBank = Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", _
  "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", _
  "W", "X", "Y", "Z")
  

'Randomly Select Characters One-by-One

  For x = 1 To Length
    Randomize
    str = str & CharacterBank(Int((UBound(CharacterBank) - LBound(CharacterBank) + 1) * Rnd + LBound(CharacterBank)))
  Next x

'Output Randomly Generated String
  RandomString = str


End Function

标签: excelvba

解决方案


推荐阅读