2013-09-25 56 views
1

我已經試過這段代碼從excel中找到使用VBA中的列表框的特定數據,它填充了sheet3範圍(E7)中的名稱列表,然後每次點擊一個項目/名稱它應該在sheet3中找到名稱,並將該行中的數據顯示在我的userform中相應的文本框中。但這不起作用。謝謝。在vba中使用listbox查找和顯示數據

Private Sub ListBox1_Click() 
Dim isRow As Long 
    If Me.ListBox1.ListIndex > -1 Then 
     isRow = Me.ListBox1.ListIndex + 1 
    End If 
    Me.Label1 = Cells(sRow, 5) 
    Me.txt_Mon_in.Text = Cells(sRow,6) 

End Sub 

從Sheet3填充數據。

Private Sub Userform_Initialize() 
Dim vCol As Variant 
Dim Lrow As Long 
    Lrow = Sheets("Sheet3").UsedRange.Rows(Sheets("Sheet3").UsedRange.Rows.Count).Row 
    vCol = Sheets("Sheet3").Range("E7:E" & Lrow).Value 
    Me.ListBox1.List = vCol 

End Sub 

回答

2

林不太清楚你在做什麼,但嘗試下面的代碼

Private Sub Userform_Initialize() 
    Dim vCol As Variant 
    Dim Lrow As Long 
    Lrow = Sheets("Sheet3").UsedRange.Rows(Sheets("Sheet3").UsedRange.Rows.Count).Row 
    vCol = Sheets("Sheet3").Range("E7:E" & Lrow).Value 
    Me.ListBox1.List = vCol 
End Sub 


Private Sub ListBox1_Click() 

    Dim selectedName As String 
    Dim i As Long 
    With ListBox1 
     For i = 0 To .ListCount - 1 
      If .Selected(i) Then 
       selectedName = .List(i) 
      End If 
     Next i 
    End With 
    Dim c As Range 
    For Each c In Sheets(3).Range("E7:E" & Sheets(3).Range("E" & Rows.Count).End(xlUp).Row) 
     If c = selectedName Then 
      Label1 = Sheets("Sheet3").Cells(c.Row, 5) 
      txt_Mon_in.Text = Sheets("Sheet3").Cells(c.Row, 6) 
     End If 
    Next c 

End Sub 

Listbox1_Click()子會遍歷E列在表3中Label1控制把名字,並把將找到的單元的(0,1)偏移到txt_Mon_in控制中。

表Sheet 3

enter image description here

用戶窗體

enter image description here

結果

enter image description here

+1

@ mehow..This正是我要找for.And作爲初學者xplanation讓我明白這個代碼是如何工作的。謝謝! – user2123999

+0

@ user2123999歡迎您!有關[**如何構建用戶窗體,請參閱此**]的更多信息(http://vba4all.wordpress.com/category/vba-macros/two-column-listbox-userform-and-saving-results-to-spreadsheet /) – 2013-09-25 14:54:50

+1

@ mehow..Gonna有更多的時間閱讀this.Sure這會給我更多的信息:D – user2123999