从集合列表中另存为随机文件名



我正在尝试保存一个文件,但作为一个小列表中的随机名称。这是我到目前为止所拥有的:

Option Explicit
Option Base 1
Public Sub SaveToDrive()
Dim categorys(5) As String
categorys(1) = "Adam"
categorys(2) = "James"
categorys(3) = "Henry"
categorys(4) = "William"
categorys(5) = "Keith"
ThisWorkbook.SaveAs Filename:="e:" & categorys(Int((5 - 1 + 1) * Rnd + 1)).Name
End Sub

目前,这会在倒数第二行的"类别"上返回无效限定符错误。

我对 VBA 完全陌生,但我想知道这是否可能,或者是否有另一种/更好的方法。

谢谢。

有关工作示例,请参见下文。 几点注意事项:

  • 默认情况下,VBA 中的数组从 0 开始。 这可以通过模块标头中的Option Base 1Option Base 0进行更改,但最安全的方法是在声明数组时简单地指定下限和上限(Dim categorys(5) --> Dim categorys(1 To 5)

  • 不知道你的- 1 + 1的目的是什么,所以我摆脱了它:Int((5 - 1 + 1 --> Int((5

  • 我拆分了表达式并添加了一些中间变量,以使事情更容易阅读和维护(& categorys(Int((5 - 1 + 1) * Rnd + 1)).Name --> Dim RandomIndex...

  • 字符串不是 VBA 中的对象,因此它们不能具有.Name


Public Sub SaveToDrive()
    Dim categorys(1 To 5) As String
    categorys(1) = "Adam"
    categorys(2) = "James"
    categorys(3) = "Henry"
    categorys(4) = "William"
    categorys(5) = "Keith"
    Dim RandomIndex As Integer
    RandomIndex = Int((5 * Rnd) + 1)
    Dim FName As String
    FName = categorys(RandomIndex)
    ThisWorkbook.SaveAs FileName:="e:" & FName
End Sub

最新更新