问题
I'm working off some example code in Word 2010, but it breaks after 10 added variables. I'm trying to understand ArrayLists in VB now.
If (ActiveDocument.Name = "template.docm") Then
With ActiveDocument
On Error Resume Next
.Variables.Add Name:="1", Value:="1"
.Variables.Add Name:="2", Value:="2"
I think the code starts adding objects to an ArrayList, but everything I've read on VBA Arraylists require declaration like:
Dim Variables As Object
Set Variables = CreateObject("System.Collections.ArrayList")
If I follow the pattern and create more objects using .Variables.add then the index breaks after 10. Right now I'm just trying to understand the list.
回答1:
From Vincent G. - "Variables is a collection property of the object Document, not an ArrayList, and does not seems to break after 10 variables were added, at least on my system."
This helped me figure out the problem was not declaring the array/collection.
My actual problem was iterating through a later loop. I previously had:
Dim z As String
int i = 1
For Each f In myarray
.Variables(i).Value = f
i = i + 1
Next f
and the parameter passed for indexing Variables is actually a string
.Variables(name)
so:
int i = 1
For Each f In myarray
z = CStr(i)
.Variables(z).Value = f
i = i + 1
Next f
fixed my problem, thanks to everyone who took time to help!
来源:https://stackoverflow.com/questions/56222346/why-does-this-arraylist-work-with-no-declaration-in-visual-basic