vba VBA如何声明具有不同数据类型的元素的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13069082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:18:08  来源:igfitidea点击:

VBA How to declare an array with elements with different datatype

vbaexcel-vbaexcel

提问by Siraj Samsudeen

I have an array that I have created to store error records and it has the following elements: Serial No,File name, error type, error cell, error cell value

我创建了一个用于存储错误记录的数组,它包含以下元素:序列号、文件名、错误类型、错误单元格、错误单元格值

As of now I have declared my array like this and then I populate the values later on.

到目前为止,我已经像这样声明了我的数组,然后我稍后填充这些值。

Dim errorArray() As String

But ideally, I want Serial Number to be a proper integer, but it is getting converted into string. I don't know how to declare this correctly so that I can have Long datatype for the first element and string for the next 3 and variant for the last one.

但理想情况下,我希望 Serial Number 是一个适当的整数,但它正在转换为字符串。我不知道如何正确声明它,以便我可以为第一个元素使用 Long 数据类型,为下一个元素使用字符串,为最后一个元素使用变体。

回答by LittleBobbyTables - Au Revtheitroad

Create a private type in your code, like this:

在您的代码中创建一个私有类型,如下所示:

Private Type ErrRecord
    SerialNo As Long
    FileName As String
    ErrorType As String
    ErrorCell As String
    ErrorCellValue As Variant
End Type

And then in your routine, call it like this:

然后在你的例程中,这样称呼它:

Dim errorArray(0) As ErrRecord
With errorArray(0)
    .SerialNo = 12345
    .FileName = "Test.xls"
    .ErrorType = "Bad error"
    .ErrorCell = "1234"
    .ErrorCellValue = "Test"
End With

回答by ORION

You'll want to create an array of type Variant. An array of type Variant can store any data type in any of its elements.

您需要创建一个 Variant 类型的数组。Variant 类型的数组可以在其任何元素中存储任何数据类型。

Dim astrItems(0 To 9)    As String
Dim varItems             As Variant

varItems = astrItems