【问题标题】:How to fill an array with strings in VBA and get its lengh?如何在 VBA 中用字符串填充数组并获取其长度?
【发布时间】:2018-07-26 20:20:06
【问题描述】:

如何在 VBA 中用字符串填充数组并获取其长度?

例如,两个单元格可能包含以下信息:

A1:“测试 1” A2:“测试 2”

Dim example As String
Dim arreglito() As String

example = Range("A2").Value


arreglito(0) = example
example= Range("A1").Value
arreglito(1)= example 
MsgBox arreglito(0)

下标超出范围

Dim example As String
Dim arreglito() As Variant

example = Range("A2").Value

arreglito(0) = example
MsgBox arreglito(0)

下标超出范围

【问题讨论】:

  • Dim arreglito(1) As String 使用前必须声明数组的大小。
  • 效果很好,是否可以重新定义数组大小?
  • ReDimArray 声明也可能使这变得不必要。
  • 查看 Redim 和 RedimPreserve。这个想法是在使用之前必须定义数组大小。或者您可以使用没有这些约束的集合。
  • 还是直接将范围读入数组然后取ubound?假设这就是 OP 所说的长度?

标签: vba excel


【解决方案1】:

这是一种将工作表中的单个列范围添加到字符串数组的方法(转置可能有一些大小限制。2^16 是吗?)。

已使用Flephal 的一行,一步将范围转换为字符串数组。

Sub AddToArray()

Dim arreglito() As String

Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = wb.Worksheets("MySheet") 'change as appropriate

Dim srcRange As Range
Set srcRange = ws.Range("A1:A3")

arreglito = Split(Join(Application.Transpose(srcRange), "#"), "#")

MsgBox UBound(arreglito) + 1

End Sub

对于通过变体数组进行多列传输:

Sub AddToArray2()

    Dim arreglito() As String
    Dim sourceArr()
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("MySheet") 'change as appropriate

    Dim srcRange As Range
    sourceArr = ws.Range("A1:C3")

    ReDim arreglito(1 To UBound(sourceArr, 1), 1 To UBound(sourceArr, 2))

    Dim x As Long
    Dim y As Long

    For x = LBound(sourceArr, 1) To UBound(sourceArr, 1)
        For y = LBound(sourceArr, 2) To UBound(sourceArr, 2)
            arreglito(x, y) = CStr(sourceArr(x, y))
        Next y
    Next x

    MsgBox UBound(arreglito, 1) & " x " & UBound(arreglito, 2)

End Sub

【讨论】:

  • 这也仅适用于单个列范围。如果范围有多于一列,它将不起作用。
  • 该死的。是的。
【解决方案2】:

您可以将整个 excel 范围读取到数组中,这比从范围单元格中读取数据要快得多。

    Sub testRerad()

        Dim arr As Variant 'no brackets needed, I prefer to use variant
        Dim numOfRows As Long, numOfCols As Long
        arr = Sheets(1).Cells(1).Resize(10, 1).value 'arr will contain data from range A1:A10

        'or
        arr = Sheets(1).Range("A1").CurrentRegion.value 'arr will contain data from all continous data startig with A1

        'get dimensions
        numOfRows = UBound(a)
        numOfCols = UBound(a, 2)

    End Sub

请注意,这将始终创建维度为 1 到 y、1 到 x 的多维数组(即使只有 1 列)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 2015-11-04
    相关资源
    最近更新 更多