查找匹配事件并复制到工作表

时间:2013-12-10 08:22:49

标签: excel vba copy find excel-2010

![在此输入图像说明] [1]嗨,我有一些VBA经验,我可以阅读和理解编码,但在查找正确的代码时遇到问题。

现在,我有一个用户形式,用户可以在其中键入他的ID,然后excel将打开数据库并搜索并返回找到的ID旁边的单元格结果。结果将被返回并覆盖标签1和标签2.当用户点击“下一个”或“上一个”按钮时,下一个或上一个结果将覆盖两个标签。

我现在拥有的代码允许我搜索找到的ID的位置,并以($ A $ 2,$ A $ 3,$ A $ 4,$ A $ 6)等格式输出位置。问题是我不确定什么是正确的功能,然后可以将其分解为“下一个”或“上一个”按钮可以引用的个别范围。

添加了我的代码

Dim cell As Range
Dim bcell As Range
Dim foundat As String
Dim oRange As Range
Dim userid As String
Dim x As Long
Dim y As Long
Dim Prob As String
Dim ws As Worksheet

Set ws = Worksheets("OFI")
Set oRange = ws.Columns(1)
userid = txt_user.Text


Set cell = oRange.Find(what:=userid, after:=Range("A1"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, searchdirection:=xlNext, MatchCase:=False)

If Not cell Is Nothing Then
    Set bcell = cell
    foundat = cell.Address
    Do
        Set cell = oRange.FindNext(after:=cell)

        If Not cell Is Nothing Then
            If cell.Address = bcell.Address Then Exit Do
            foundat = foundat & ", " & cell.Address
    Else
        Exit Do
    End If
Loop
Else
    msgbox userid & "not found"
    Exit Sub
End If

capproblem_output.Caption = foundat


Exit Sub

1 个答案:

答案 0 :(得分:0)

您需要添加两个名为cmdNext&的命令按钮。 cmdPrev,使用名称capproblem_output2标记以运行以下代码。将代码复制到userform代码部分。

Public foundat As String

Private Sub cmdNext_Click()
    capproblem_output.Caption = ActiveCell.Offset(1, 1)
    capproblem_output2.Caption = ActiveCell.Offset(1, 1)
    ActiveCell.Offset(1, 0).Select
End Sub

Private Sub cmdPrev_Click()
    capproblem_output.Caption = ActiveCell.Offset(-1, 1)
    capproblem_output2.Caption = ActiveCell.Offset(-1, 1)
    ActiveCell.Offset(-1, 0).Select
End Sub

Private Sub CommandButton1_Click()
    Main
End Sub


Sub Main()
    Dim cell As Range
    Dim bcell As Range

    Dim oRange As Range
    Dim userid As String
    Dim x As Long
    Dim y As Long
    Dim Prob As String
    Dim ws As Worksheet

    Set ws = Worksheets("OFI")
    Set oRange = ws.Columns(1)
    userid = UserForm1.txt_user.Text


    Set cell = oRange.Find(what:=userid, after:=Range("A1"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, searchdirection:=xlNext, MatchCase:=False)

    If Not cell Is Nothing Then
        Set bcell = cell
        foundat = cell.Address
        Do
            Set cell = oRange.FindNext(after:=cell)

            If Not cell Is Nothing Then
                If cell.Address = bcell.Address Then Exit Do
                foundat = foundat & ", " & cell.Address
        Else
            Exit Do
        End If
    Loop
    Else
        MsgBox userid & "not found"
        Exit Sub
    End If

    capproblem_output.Caption = Range(foundat).Offset(0, 1)
    capproblem_output2.Caption = Range(foundat).Offset(0, 1)
End Sub