ExcelVBA:尝试创建搜索和读取数据的userform

时间:2016-09-26 13:44:29

标签: excel vba excel-vba

我正在尝试创建一个可以搜索数据并将其读入自身的用户表单。为了记录,我正在关注this tutorial。我的表单的工作方式是你必须键入一个ID号,以便它知道你想要什么数据(在某种意义上有点像Vlookup)。问题是当我按下命令按钮时没有检索到数据!这是我的代码:

Private Sub CommandButton1_Click()

row_number = 0
Do
DoEvents
row_number = row_number + 1
item_in_review = Sheets.("Ark1").Cells(row_number, "A")
    If item_in_review = TextBox1.Text Then
       TextBox2.Text = Sheets("Ark1").Cells(row_number, "B")
       TextBox3.Text = Sheets("Ark1").Cells(row_number, "C")
    End If
Loop Until item_in_review = ""

End Sub

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

这是我通常做的事情。尝试将所有(或仅第一个)结果加载到数组中。不只是使用该行号来检索所有其他信息。

rowsArray(i) = ActiveSheet.Range("A:A").EntireColumn.Find _
                (What:=productsArray(i), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False).Row

答案 1 :(得分:0)

首先关闭

Sheets.("Ark1").Cells(row_number, "A")

必须是

Sheets("Ark1").Cells(row_number, "A")

然后我认为您必须首先检查TextBox1.Text

中的任何有效值

如下:

Option Explcit

Private Sub CommandButton1_Click()
    Dim row_number As Long

    With Me
        If .TextBox1.Text = "" Then
            MsgBox "please input valid text in 'TextBox1'", vbExclamation
            Exit Sub
        End If
        Do
            DoEvents '<-- what's this for?
            row_number = row_number + 1
            item_in_review = Sheets("Ark1").Cells(row_number, "A")
            If item_in_review = .TextBox1.Text Then
               .TextBox2.Text = Sheets("Ark1").Cells(row_number, "B")
               .TextBox3.Text = Sheets("Ark1").Cells(row_number, "C")
               Exit Sub '<--| if you want the first match to fill TextBox2 and TextBox3
            End If
        Loop Until item_in_review = ""
    End With
End Sub