如何修复列表显示,选择正确但检索数据不正确

时间:2019-04-30 12:02:38

标签: excel vba

我想在选择ListBox(lstDisplay)中的项目时检索数据并将其显示在我的textField中。

记录显示在ListBox(lstDisplay)中,当我单击单个记录时,这些记录将显示在文本字段中,问题是它显示不正确

请查看屏幕截图Screenshot

请参阅我的代码:

Private Sub lstDisplay_Change()
    Dim i As Integer
    For i = 1 To Range("A65356").End(xlUp).Row  
        If lstDisplay.Selected(i) Then
            Rows(i + 10).Select
            txtSearch.Text = Sheet1.Cells(i, 1)
            txtLname.Text = Sheet1.Cells(i, 2)
            txtFname.Text = Sheet1.Cells(i, 3)
            cmbCourse.Value = Sheet1.Cells(i, 4)
            cmbYear.Value = Sheet1.Cells(i, 5)
        End If      
    Next i
End Sub

2 个答案:

答案 0 :(得分:1)

lstDisplay的计数器从0开始,而Cells(row, column)的行计数从1开始。因此,必须将i + 1用于单元格。

实际上,我建议循环浏览列表框而不是单元格

Private Sub lstDisplay_Change()
    Dim i As Integer
    For i = 0 To lstDisplay.ListCount - 1  
        If lstDisplay.Selected(i) Then
            'Rows(i + 10).Select 'not needed
            txtSearch.Text = Sheet1.Cells(i + 1, 1)
            txtLname.Text = Sheet1.Cells(i + 1, 2)
            txtFname.Text = Sheet1.Cells(i + 1, 3)
            cmbCourse.Value = Sheet1.Cells(i + 1, 4)
            cmbYear.Value = Sheet1.Cells(i + 1, 5)
        End If      
    Next i
End Sub

答案 1 :(得分:0)

AFAIK列表框选择是基于0的,因此应将诀窍更改为i-1

Private Sub lstDisplay_Change()
  Dim i As Integer
  For i = 1 To Range("A65356").End(xlUp).Row
    If lstDisplay.Selected(i-1) Then
       Rows(i + 10).Select
       txtSearch.Text = Sheet1.Cells(i, 1)
       txtLname.Text = Sheet1.Cells(i, 2)
       txtFname.Text = Sheet1.Cells(i, 3)
       cmbCourse.Value = Sheet1.Cells(i, 4)
       cmbYear.Value = Sheet1.Cells(i, 5)
     End If
   Next i
End Sub