我用名爲ComboBox1的組合框和名爲TextBox1的文本框(啓用了多行屬性)製作了一個用戶窗體。當您加載用戶窗體(UserForm1)時,您的Initialize事件將觸發正在執行的UserForm_Initialize()。這將與所有主機一起填充組合框。當您選擇一個主機時,ComboBox1_Change()事件將觸發並輸出類似HOST2 Guest5 Guest6 Guest7 Guest8
的文本框。但是,您可以將輸出更改爲您想要的任何位置。
Option Explicit
Dim allHosts As Range
Private pHostRow As Integer
Dim hostColumn As Integer
Private Sub UserForm_Initialize()
Dim Host As Range
Dim firstHost As Range
Dim lastHost As Range
Dim lastHostRow As Integer
hostColumn = 1
Set firstHost = Cells(1, hostColumn)
lastHostRow = firstHost.End(xlDown).Row
Set lastHost = Cells(lastHostRow, hostColumn)
Set allHosts = Range(firstHost, lastHost)
For Each Host In allHosts
ComboBox1.AddItem Host.Text
Next Host
End Sub
。
Private Sub ComboBox1_Change()
Dim selectedHost As String
selectedHost = ComboBox1.Text
pHostRow = allHosts.Find(selectedHost).Row
Dim guest As Range
Dim allGuests As Range
Dim firstGuest As Range
Dim lastGuest As Range
Dim lastGuestCol As Integer
Dim Host As Range
Set Host = Cells(pHostRow, hostColumn)
lastGuestCol = Host.End(xlToRight).Column
Set firstGuest = Host.Offset(0, 1)
Set lastGuest = Cells(pHostRow, lastGuestCol)
Set allGuests = Range(firstGuest, lastGuest)
TextBox1.Text = selectedHost
For Each guest In allGuests
TextBox1.Text = TextBox1.Text & selectedHost & guest.Text & vbCrLf
'if you weren't outputting this to a textbox you wouldn't use the vbCrLf,
'instead you would iterate to the next line in your output range.
Next guest
End Sub
你可以看到你如何修改這個,所以你將通過所有的主機循環(即在填充組合框),併爲每個主機呼叫ComboBox1_Change()事件(改名當然,並提出了常規子)將所有客人輸出到您在另一個工作表上迭代的某個範圍。
希望它能幫助!
您的示例會在一臺主機下返回所有客人嗎? Guest4會包含在內嗎? – Brad
是的,對不起,我沒有完全闡述。關鍵是要有兩列,「客人」和相應的「主人」,以表示客人的所有價值觀。假設我有一個包含所有客人的單獨列。 –