在Excel VBA中构build数组时,下标超出范围?

下面是构build属性的代码,然后将其打印为xml文件。 每次运行它时,都会说下标超出范围,突出显示属性2。 列40-41应该在定义的范围内。

我认为这个问题可能是因为我不应该使用“ElseIf”。 当我只将它作为属性1和属性2运行时,它使用“Else”语句时正常工作。 也许我错误地定义了我的数组,无论哪种方式我都找不到答案,需要一些新的眼睛。

Sub ILikeFruits() Dim headers(), data(), attributes1(), attributes2(), attributes3(), _ attributes4(), attributes5(), attributes6(), attributes7(), attributes8(), attr$, r&, c& ' load the headers and data to an array ' headers = Cells(1, 1).Resize(1, 104).Value data = Cells(2, 1).Resize(10, 104).Value ' set the size for the attributes ' ReDim attributes1(1 To 39) ReDim attributes2(40 To 41) ReDim attributes3(42 To 51) ReDim attributes4(52 To 65) ReDim attributes5(66 To 69) ReDim attributes6(70 To 89) ReDim attributes7(90 To 97) ReDim attributes8(98 To 104) ' open file and print the header ' Open "C:\desktop\XML Update\Simulation\XML tests (Attributes)\DataTest.xml" For Output As #1 Print #1, "<Fruits>" Print #1, " <Tasty_Fruits>" ' iterate each row ' For r = 2 To UBound(data) ' iterate each column ' For c = 1 To UBound(data, 2) ' build each attribute ' attr = headers(1, c) & "=""" & data(r, c) & """" If c <= 39 Then attributes1(c) = attr ElseIf 40 <= c <= 41 Then 'Subscript out of range attributes2(c) = attr ElseIf 42 <= c <= 51 Then attributes3(c) = attr ElseIf 52 <= c <= 65 Then attributes4(c) = attr ElseIf 66 <= c <= 69 Then attributes5(c) = attr ElseIf 70 <= c <= 89 Then attributes6(c) = attr ElseIf 90 <= c <= 97 Then attributes7(c) = attr ElseIf 98 <= c <= 104 Then attributes8(c) = attr End If Next ' print the row ' Print #1, " <Fruits_By_Color " & Join(attributes1, " ") & " >" Print #1, " <Small_Red_Fruits>" Print #1, " <Cranberry " & Join(attributes2, " ") & " />" Print #1, " </Small_Red_Fruits>" Print #1, " <Big_Red_Fruits>" Print #1, " <Apple " & Join(attributes3, " ") & " />" Print #1, " <Pomegranate " & Join(attributes4, " ") & " />" Print #1, " <Tomato " & Join(attributes5, " ") & " />" Print #1, " </Big_Red_Fruits>" Print #1, " <Yellow_Fruits>" Print #1, " <Small_Yellow_Fruits " & Join(attributes6, " ") & " >" Print #1, " <Banana " & Join(attributes7, " ") & " />" Print #1, " <Lemon " & Join(attributes8, " ") & " />" Print #1, " </Small_Yellow_Fruits>" Print #1, " </Yellow_Fruits>" Print #1, " </Fruits_By_Color>" Next ' print the footer and close ' Print #1, " </Tasty_Fruits>" Print #1, "</Fruits>" Close #1 End Sub 

问题出在你的If语句上 – 你不能像VBA那样链接条件语句。 在VBA,他们将被评估从左到右,所以这…

 40 <= 50 <= 41 

变成这个:

 (40 <= 50) <= 41 

expression式40 <= 50返回True ,它变成…

 True <= 41 

…和True在VBA中转换为-1的数值,所以最终…

 If -1 <= 41 Then 

碰巧是True和超出范围的索引。

所以,把你的testing和:

 ElseIf 40 <= c And c <= 41 Then 

以前的答案是正确的,但作为一个风格的东西,这是一个完美的地方使用Select .. Case语句:

 Select Case c Case 1 To 39 attributes1(c) = attr Case 40 To 41 attributes2(c) = attr Case 42 To 51 attributes3(c) = attr ... ' Fill in the other possibilities End Select