2016-06-16 52 views
4

我有一個excel電子表格中的長列表,並且對於每個單元格我想創建一個新對象,但我無法弄清楚如何去做。爲每個單元格創建新對象

我有類似:

Dim k As Integer 
k = 0 

Do 

    If ActiveCell.Offset(k, 0).Value = "" Then Exit Do 
    Dim Player&k As New CPlayer 

     'Attempting to create a new object with name Player0, Player1, ... 

    Set Player&k.Name = ActiveCell.Offset(k, 0).Value 
    k = k + 1 
Loop 

正如你可能會說,我不知道很多關於VBA或面向對象編程,我只是有一個任務,我試圖完成。上面的代碼導致編譯錯誤,所以顯然不是這樣做的正確方法,有沒有簡單的方法來做我想要的或不是真的?

+1

你不能像這樣聲明變量。 'CPlayer'是一個班級? – findwindow

+0

是的,CPlayer是一個具有名稱屬性的類。那麼這是不可能的? – Qiri

+1

您可以創建一個類的數組。雖然XD – findwindow

回答

3

試試這個。從k = 0開始會弄亂一些東西。更改,以便它以1開頭。

Dim Players As Collection 
Set Players = New Collection 

Dim Player As CPlayer 

Dim k As Integer 
k = 1 

Do 
    If ActiveCell.Offset(k-1, 0).Value = "" Then Exit Do 
    Set Player = New CPlayer 
    Players.Add Player 

    Players(k).Name = ActiveCell.Offset(k-1, 0).Value 
    k = k + 1 
Loop 
1

我會避免類對象的數組,並使用集合來代替。在一些圈子中,這些可能被認爲非常接近相同的東西,但是有一些本質的區別,比如不需要ReDim擴展集合。

CPlayer類

Option Explicit 

Private pName As String 

Public Property Get Name() As String 
    Name = pName 
End Property 
Public Property Let Name(val As String) 
    pName = val 
End Property 

模塊1碼片

Option Explicit 

Sub playerNames() 
    Dim Players As Collection 
    Dim player As CPlayer, k As Long 

    Set Players = New Collection 

    With ActiveSheet 'this would be better as something like With Worksheets("Sheet1") 
     For k = 2 To .Cells(Rows.Count, "F").End(xlUp).Row 
      If CBool(Len(.Cells(k, "F").Value2)) Then 
       Set player = New CPlayer 
       player.Name = .Cells(k, "F").Value2 
       Players.Add player 
      End If 
     Next k 

     'enumerate the payer names to the Immediate window 
     For Each player In Players 
      Debug.Print player.Name 
     Next player 

     'send the second and third player's name to the Immediate window 
     Debug.Print Players(2).Name 
     Debug.Print Players(3).Name 

    End With 
End Sub 

這樣建立你的球員的集合,並提供檢索,請將.Name屬性的兩種方法。

+0

@Fredrik提出的答案與上述基本相同,但提供了將工作表中的名稱應用於集合的不同方法。 – Jeeped

+0

他在24分鐘內擊敗了你。剛剛失去了我對你的尊重= P – findwindow

+0

建立一個班級並重寫子程序和樣本數據需要幾分鐘時間(等待OP回覆評論後要求澄清)。 :( – Jeeped

相關問題