如何使用表单在Excel和活动工作表中的另一个工作表中找到值?

时间:2012-07-27 17:46:41

标签: excel vba excel-vba

嗯,这是我的问题到目前为止,我有一个VB在这种形式的表单,用户输入一个数字我想要做的是在Sheet2 excel搜索如果我得到这个数字(如果被买),并在活动表“数据”如果已经被捕获,最后将它放在Sheet1的最后一个空A行中。

到目前为止,我有这个。

Private Sub CommandButton1_Click()
Me.TextBox1.Text = ""
Me.TextBox2.Text = ""
End Sub

Private Sub CommandButton2_Click()
Dim lastrow As Double
Dim frange As Range


lastrow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count

If TextBox1.Text = TextBox2.Text Then


Sheets("Sheet2").Activate
ActiveSheet.Range("A2").Select

If Range("A2:A200").Find(What:=TextBox2.Value _
, After:=ActiveCell, LookIn:=xlValues, LookAt:= _
xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False).Activate Then

Sheets("Datos").Activate

If Range("A3:A200").Find(What:=TextBox2.Value _
, After:=ActiveCell, LookIn:=xlValues, LookAt:= _
xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False).Activate Then

MsgBox ("This number is already registred")

Else

Cells(lastrow + 1, 1) = TextBox2.Value

End If

Else

MsgBox ("The number has not been buyed")

End If

Else

MsgBox ("The number are not the same")

End If

End Sub

我真的希望有人可以帮助我,因为我被困住了,我没有看到答案。

由于

抱歉我的英文

1 个答案:

答案 0 :(得分:1)

<强> UNTESTED

请查看这是否是您正在尝试的内容?

Private Sub CommandButton1_Click()
    Me.TextBox1.Text = "": Me.TextBox2.Text = ""
End Sub

Private Sub CommandButton2_Click()
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim aCell As Range, bCell As Range
    Dim lrow As Long

    Set ws1 = Sheets("Datos"): Set ws2 = Sheets("Sheet2")

    If TextBox1.Text = TextBox2.Text Then
        Set aCell = ws2.Columns(1).Find(What:=TextBox2.Value _
                , LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, MatchCase:=False)
        If Not aCell Is Nothing Then
            Set bCell = ws1.Columns(1).Find(What:=TextBox2.Value _
                    , LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, MatchCase:=False)
            If Not bCell Is Nothing Then
                MsgBox ("This number is already registred")
            Else
                '~~> This will write to sheet "Datos". if you want to
                '~~> write to sheet Sheet2 then change ws1 to ws2 below
                With ws1
                    lrow = ws1.Range("A" & .Rows.Count).End(xlUp).Row + 1
                    .Cells(lrow, 1) = TextBox2.Value
                End With
            End If
        Else
            MsgBox ("The number has not been buyed")
        End If
    Else
        MsgBox ("The number are not the same")
    End If
End Sub