如何声明可变数量的索引字符串?

时间:2016-01-20 07:18:30

标签: excel vba excel-vba

我希望声明多个变量,并且要声明的变量数取决于输入,所以它类似于:

Sub Main()
Dim TotalNumber As Long
    TotalNumber = InputBox("Please enter total number of words")
Dim i As Long
Dim MsgDisp As String
Dim Words(1 To TotalNumber) As String
For i = 1 To TotalNumber
    String(i) = InputBox("Please type the words for number " & i)
    MsgDisp = MsgDisp & String(i) & Chr(10)
Next i
MsgBox(MsgDisp)
End Sub

但是我在第6行得到了“需要常量表达式”错误。 任何帮助表示赞赏...

3 个答案:

答案 0 :(得分:2)

这样做的方法是首先声明数组没有边界,然后重新调整它:

Dim Words() As String
'Other code
ReDim Words(1 To TotalNumber)

在代码的进一步过程中,您甚至可以扩展数组。但为了避免数组被破坏,您可以添加Preserve关键字:

TotalNumber = TotalNumber + 1
ReDim Preserve Words(1 To TotalNumber)

编辑在redims之后删除“As String”。再次编辑以添加Preserve关键字。

答案 1 :(得分:0)

应该是单词(i)我想。不是字符串。另外,我不认为你昏暗会接受这样的变量。

答案 2 :(得分:0)

使用以下子目录:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Shopping list</title>
  <link href='https://fonts.googleapis.com/css?family=Old+Standard+TT:400,700,400italic' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet'>
  <link href='https://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet'>
  <link href="css/style.css" rel="stylesheet">
</head>

<body id="background">

  <div class="container">
    <h2>Shopping List</h2>
    <h3> </h3>
    <div class="form-list">
      <form>
        <input type="text" id="new-text" placeholder="Add item to list" />
        <input type="number" id="quantity" />
        <button class="submit"></button>


      </form>

      <ul id="list">

      </ul>
    </div>
  </div>
  <div class="footer">

  </div>
  <script src="http://code.jquery.com/jquery.min.js"></script>
  <script src="js/jquery.js"></script>
</body>

</html>