首页 > 解决方案 > Visual Basic 查询 (excel)

问题描述

我刚刚开始了一份新工作,并试图在 excel 中使用 VBA 将值存储在多维数组中。

所以我首先想在列中搜索值,当它们出现时,我想将它们存储一次,并分配一个产品编号,每次在该列中遇到一个新的唯一字符串值时,该编号都会增加。然后只需将数字打印到单元格并仅在其递增时更改它/

值将是字符串,(产品样式)。产品编号将是一个数字。(int)

是否有可能在 VBA 中为 excel 执行此操作。我在网上读到你不能在同一个数组中使用不同的数据类型。

抱歉 VBA 新手,任何帮助都会很棒。如果我最好在 excel 中使用普通函数,请告诉我。

标签: excelvbaexcel-formula

解决方案


您可以将数组声明为 Variant,然后您可以在数组中存储不同的类型。例如

Sub test()
    Dim arr() As Variant
    Dim i As Long
    
    ReDim arr(0 To 1)
    
    arr(0) = "hi"
    arr(1) = 1
    
    For i = LBound(arr, 1) To UBound(arr, 1)
        Debug.Print arr(i)
        Debug.Print VarType(arr(i))
    Next
End Sub

这会在即时窗口中打印以下内容

hi
 8 ' This corresponds to the type String
 1 
 2 ' This corresponds to the type Integer

编辑

根据问题,是的,您可以将不同类型的数组作为 Variant-Array 中的条目。例如:

Sub test2()
    Dim arr As Variant
    Dim str_a(3) As String
    Dim lng_a(8) As Long
    Dim i As Long, j As Long
    
    For i = LBound(str_a, 1) To UBound(str_a, 1)
        str_a(i) = "hi " & i
    Next
    
    For i = LBound(lng_a, 1) To UBound(lng_a, 1)
        lng_a(i) = i
    Next
    
    ReDim arr(0 To 1)
    
    arr(0) = str_a
    arr(1) = lng_a
    
    For i = LBound(arr, 1) To UBound(arr, 1)
        Debug.Print VarType(arr(i))
        
        For j = LBound(arr(i), 1) To UBound(arr(i), 1)
            'Do Stuff with the arrays
        Next
    Next
End Sub

这打印

8200 
8195

一个数组总是有VarType8192 + 类型的值。例如String,值为 8,因此类型 String 的数组有 8200 (8192+8)。


推荐阅读