在Word中搜索数组(Visual Basic for Applications)

时间:2011-05-19 08:35:34

标签: arrays vba ms-word word-vba

我在Word中设置了三个数组。数组如下:

tacData = Array("32064600", "33001000", "33001100", "33002400", "33003000", "33002400", "35011001", "35013200", "35124100", "35124100")
makeData = Array("Alcatel", "Alcatel", "Sagem", "Samsung", "AEG Mobile", "Samsung", "Nokia", "Maxon", "Siemes", "Nokia")
modelData = Array("One Touch EasyHD", "91009109MB2", "RC410G14", "SGH-200", "Sharp TQ6", "SGH-5300", "DCT-3", "MX6832", "MC399 Cellular Termnial", "DCT-4")

我已经创建了一个用户表单,它从用户那里获得TAC(值)。我可以获取此值并在第一个数组中搜索它并获取其ID,以便我可以从其他两个数组中获取make和model吗?我尝试过使用我发现的一些代码示例,但它们似乎不适用于Word抛出错误。它们就像Application.Match。

另一方面,是否有更好的方法来存储这些信息而不是三个数组?

1 个答案:

答案 0 :(得分:3)

我认为你需要一个集合对象。请看下面的代码

Dim tacData() As Variant, makeData() As Variant, modelData() As Variant
tacData = Array("32064600", "33001000", "33001100", "33002400", "33003000", "33002401", "35011001", "35013200", "35124100", "35124101")
makeData = Array("Alcatel", "Alcatel", "Sagem", "Samsung", "AEG Mobile", "Samsung", "Nokia", "Maxon", "Siemes", "Nokia")
modelData = Array("One Touch EasyHD", "91009109MB2", "RC410G14", "SGH-200", "Sharp TQ6", "SGH-5300", "DCT-3", "MX6832", "MC399 Cellular Termnial", "DCT-4")

Dim i As Integer, N As Integer
N = UBound(tacData, 1) 'Get the data size
Dim item As Phone      'Temp variable for creating elements into a collection

Dim list As New VBA.Collection  'Define a new collection
For i = 1 To N
    Set item = New Phone        'Assign a new Phone object
    With item
        .TAC = tacData(i)       'Assign values to the phone
        .Make = makeData(i)
        .Model = modelData(i)
    End With
    list.Add item, item.TAC     'Add the phone to the list with a KEY
    Set item = Nothing
Next i

Dim TAC As String
TAC = "33002400"                'get user input

Set item = list(TAC)            '** lookup Phone using Key **

If Not item Is Nothing Then     ' Show results
    Debug.Print item.TAC, item.Make, item.Model
Else
    Debug.Print "Not Found"
End If

它适用于一个名为'Phone'的新类,其中包含

Option Explicit    
Public TAC As String
Public Make As String
Public Model As String

并通过此菜单项插入VBA,并在项目树中将其重命名为“Phone”
enter image description here

要求是'TAC'代码是唯一的。在你的情况下它不是,我不得不改变一些数字,使它们独一无二。如果在现实生活中有多个具有相同TAC代码的手机,该怎么做呢?

PS。欢迎来到面向对象编程的世界。这是你的第一步。