在用户窗体初始化之后更新一个用户窗体列表框

是否有任何方法来更新UserForm之外的UserFormListBox

为什么? 我正在build造一个二十一点游戏,并使用列表框来告诉用户他们拥有哪些牌/经销商。 我希望使用一个简单的子( ShowCards )将项目添加到列表框,但我遇到了问题:

在这里输入图像说明

Playbutton调用位于普通模块中的PlayBlackjack

 Option Explicit Dim cards As New Collection Sub ShowGame() UFDisplay.Show End Sub Sub PlayBlackjack() 'fill the cards collection with 5 shuffled decks PrepareCards Dim i As Integer Dim userHand As New Collection Dim dealerHand As New Collection 'deal cards (removing the dealt cards from the cards collection) For i = 1 To 2 DealCard cards, userHand DealCard cards, dealerHand Next i ShowCards userHand, UFDisplay.UserHandList <-- ERROR HERE (Type mismatch) 'more code to follow End Sub Private Sub ShowCards(hand As Collection, list As ListBox) Dim i As Integer For i = 1 To hand.Count list.AddItem hand(i).CardName Next i End Sub 

让我知道如果你认为你需要更多的代码。 hand是Card类的集合, .CardName返回类似于3 of Hearts

我读的一切似乎告诉我,初始化后,用户窗体是静态的,所以我需要在添加新项目后以某种方式刷新它。 我试过Userform.Repaint没有运气。

那么如果真的没有别的办法,我应该声明userHanddealerHand为全局variables,更新它们并调用Useform_Initialize来获取更新后的值并将其显示给用户? 鉴于游戏的性质是可以为两个玩家分配更多的卡,所以每次游戏多次重新初始化用户表单似乎是不明智的。

所有的build议欢迎。 如果你认为我应该完全不同的做法,我仍然很想听到(但对工作表解决scheme不太感兴趣)

更新#1为了清楚起见,ShowGame由工具上的一个button调用,然后从用户窗体上的播放button调用PlayBlackjack(在用户窗体代码中没有其他)

啊,我明白了。 您不能将listBox参数声明为ListBox。 后者保留给Activex控件,而不是VBA控件。 将ShowCards子的签名更改为:

 Private Sub ShowCards(hand As Collection, list As Control) '<~~ or MSForms.ListBox, or simply as Object... 

你也可以使用类的手,并设置类列表框为表单列表框,例如,类clsHand

 Public colHand As collection Public lstToUpdate As MSForms.ListBox Private Sub Class_Initialize() Set colHand = New collection End Sub Friend Function AddCard(card As clsCard) colHand.Add card, CStr(colHand.Count) If Not lstToUpdate Is Nothing Then lstToUpdate.AddItem card.strCardName End If End Function 

这是在一个窗体中使用

 Private clsPlayerHand As clsHand Private Sub UserForm_Initialize() Set clsPlayerHand = New clsHand Set clsPlayerHand.lstToUpdate = Me.ListBox1 End Sub Private Sub CommandButton1_Click() Dim clsC As New clsCard clsC.strCardName = "one" clsPlayerHand.AddCard clsC End Sub 

编辑:build议,

使用数字和套装名称为您的卡,然后你可以做以下事情,说启用拆分button,顺便说一句,你会使用手arrays然后arrHands(x)…

 Public colHand As collection Public lstToUpdate As MSForms.ListBox Public cmdSplitButton As MSForms.CommandButton Private Sub Class_Initialize() Set colHand = New collection End Sub Friend Function AddCard(card As clsCard) colHand.Add card, CStr(colHand.Count) If Not lstToUpdate Is Nothing Then lstToUpdate.AddItem card.CardName End If If Not cmdSplitButton Is Nothing Then If colHand.Count = 2 Then _ cmdSplitButton.Enabled = colHand(1).NumericPart = colHand(2).NumericPart End If End Function 

看看如何充分发挥自己的潜力,观察事件,对某些事情做出反应。