2016-01-20 55 views
0

我要聲明多個變量,變量申報數量取決於輸入所以它是這樣的:如何聲明可變數量的索引字符串?

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號線 任何幫助讚賞...

回答

2

做到這一點的方法是首先聲明沒有界限的數組,然後redimming它:

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

在你的代碼,你可以進一步課程甚至可以擴大陣列。但要避免被調臺的陣列,您可以添加保留關鍵字:

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

編輯redims後刪除「作爲字符串」。再次編輯添加Preserve關鍵字。

+0

謝謝!這就是它。我不知道尺寸必須單獨定義。 –

0

應該是詞(我)認爲。不是字符串。另外,我不認爲你是昏暗的會接受一個變量的方式。

0

使用以下子:

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

你必須用像'ReDim Words(TotalNumber)'這樣的'ReDim'來重新調整數組長度。 – harun24hr