2011-05-19 16 views
1

我在Word中設置了三個數組。陣列如下:在Word中搜索數組(Visual Basic for Applications)

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,以便從另外兩個數組中獲得製造商和型號?我曾嘗試使用我發現的一些代碼示例,但它們似乎不適用於引發Word的錯誤。他們是像Application.Match的東西。

在附註中,是否有更好的方式來存儲這些信息而不是三個數組?

+0

我注意到TAC「33002400」被定義了兩次,使它不適合集合對象。 – ja72 2011-05-19 12:51:56

回答

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 

它與一個叫含

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

「電話」和插入VBA通過該菜單項新類的代碼,並在項目樹重命名爲「手機」
enter image description here

要求是'TAC'代碼是唯一的。在你的情況下,它不是,我不得不改變一些數字,以使它們獨一無二。如果在現實生活中存在多個具有相同TAC代碼的電話,那麼必須考慮怎麼做。

PS。歡迎來到面向對象編程的世界。這是你的第一步。

+0

+1表示歡迎(其餘的也很好)。 – RolandTumble 2011-05-19 20:22:04