VBA调整数组大小,用户选择其大小

时间:2016-07-08 18:03:12

标签: vba excel-vba excel

我正在尝试创建一个关键字字符串数组。字符串数组将具有一定数量的列(3种不同水果的不同数量的关键字:苹果,香蕉,橙色)。但是,对于每个水果,每行的列将根据用户要查找的关键字数量而不同。用户可能正在寻找苹果的1个关键字,香蕉的2个关键字以及橙色的3个关键字。当这一切都说完了,我想要一个3xC的字符串数组,其中C是最大数量的关键字,而未填充的单元格是空的。这是我到目前为止的代码,但我不确定如何对数组进行维度化。

Public strTemp(0 To 2, 0 To 100) As Variant
Sub GetKeyWords()

Dim numKeyA As Integer
Dim numKeyB As Integer
Dim numKeyO As Integer



'Ask user for integer value of keywords looking for
numKeyA = InputBox("How many keywords would you like to search for the A? (Integer)", "A Integer Value Please")

'Ask user for the specific keywords
For k = 1 To numKeyA

    'Save keywords into strTemp array
    strTemp(0, k - 1) = InputBox("Please enter keyword" & k)

Next

numKeyB = InputBox("How many keywords would you like to search for the B? (Integer)", "B Integer Value Please")

For a = 1 To numKeyB

    'Save keywords into strTemp array
    strTemp(1, a - 1) = InputBox("Please enter keyword" & a)

Next

numKeyC = InputBox("How many keywords would you like to search for the C? (Integer)", "C Integer Value Please")

For b = 1 To numKey777

    'Save keywords into strTemp array
    strTemp(2, b - 1) = InputBox("Please enter keyword" & b)



    maxColumn = WorksheetFunction.Max(numKeyA, numKeyB, numKeyC)
    ReDim strTemp(2, maxColumn)



Next


End Sub

现在代码的方式,我尝试在最后重新调整数组以根据最大列调整大小时出错。如果我没有在开始时调整代码的大小,我会收到strTemp(0,k-1)= InputBox(“请输入关键字”& k)的错误“下标超出范围”。

2 个答案:

答案 0 :(得分:1)

Public strTemp() As Variant

省略声明中的索引。然后,在尝试将任何内容放入ReDim之前,您需要strTemp。如果您先完成所有三个InputBox es,那么您就可以调整strTemp的大小,然后读入关键字。

或者,使用

ReDim strTemp(2, numKeyA)

在第一个InputBox之后,然后说

ReDim Preserve strTemp(2, IIf(numKeyA>numKeyB, numKeyA, numKeyB))

在第二个InputBox之后(IIf是这样你不会缩小数组)。 Preserve将保留已存在的值。同样,在第三个InputBox之后,

ReDim Preserve strTemp(2, maxColumn)

答案 1 :(得分:1)

试试这个: 有关详细信息,请参阅注释。

   Sub test()

    Dim lCtrCol_New     As Long
    Dim lCtrRow_New     As Long
    Dim lInst           As Long
    Dim arrNew()



    '/ Start New Array
    ReDim arrNew(1 To 3, 1 To 1)

    '/ Add Values
    arrNew(1, 1) = "Apple"
    arrNew(2, 1) = "Orange"
    arrNew(3, 1) = "Tomato"

    '/ Loop and assign unique values
    For lCtrRow_New = LBound(arrNew) To UBound(arrNew)
      lInst = Val(InputBox("No. of Keywords for " & arrNew(lCtrRow_New, 1), ""))
                If lInst + 1 > UBound(arrNew, 2) Then
                    ReDim Preserve arrNew(1 To 3, 1 To lInst + 1)
                End If

                For lCtrCol_New = LBound(arrNew, 2) To lInst
                    arrNew(lCtrRow_New, lCtrCol_New + 1) = InputBox("Please enter keyword #" & lCtrCol_New & " for " & arrNew(lCtrRow_New, 1))
                Next

       Next
End Sub