如何在列中查找字符串值并在该行的所有单元格中返回值?

时间:2019-05-09 17:14:14

标签: excel vba userform

我正在创建一个用户表单,该表单将要求提供报价单,在找到报价单后填充数据,并更新所有信息。我当前正在使用的宏代码无法与此新的用户表单一起使用。

Search and update image

我设法用下面的代码填充文本框,但是如果更改任何文本框值,现在我需要它来实际更新单元格。

Private Sub CommandButton1_Click()

Dim ws As Worksheet
Dim strSearch As String
Dim aCell As Range
Dim Sold As String, Soldlr As Long

Set ws = Sheets("Data Entry")

With ws
    strSearch = Me.TextBox1.Value
    Set aCell = .Columns(2).Find(What:=strSearch, LookIn:=xlValues, _
                                 LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                                 MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        Me.TextBox1.Text = aCell.Value
        Me.TextBox2.Text = aCell.Offset(, -1).Value
        Me.TextBox3.Text = aCell.Offset(, 0).Value
        Me.TextBox4.Text = aCell.Offset(, 1).Value
        Me.TextBox5.Text = aCell.Offset(, 2).Value
        Me.TextBox6.Text = aCell.Offset(, 3).Value
        Me.TextBox7.Text = aCell.Offset(, 4).Value
        Me.TextBox8.Text = aCell.Offset(, 5).Value

    Else
        MsgBox "Quote Number " & strSearch & " Not Found. Try Again"

    End If

    Exit Sub
End With
End Sub

Private Sub CommandButton2_Click()

Dim ws As Worksheet
Dim strSearch As String
Dim aCell As Range
Dim Sold As String, Soldlr As Long

Set ws = Sheets("Data Entry")

With ws
    strSearch = Me.TextBox1.Value
    Set aCell = .Columns(2).Find(What:=strSearch, LookIn:=xlValues, _
                                 LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                                 MatchCase:=False, SearchFormat:=False)

    If Not aCell Is Nothing Then
        aCell.Offset(, -1).Value = Me.TextBox2.Text
        aCell.Offset(, 0).Value = Me.TextBox3.Text
        aCell.Offset(, 1).Value = Me.TextBox4.Text
        aCell.Offset(, 2).Value = Me.TextBox5.Text
        aCell.Offset(, 3).Value = Me.TextBox6.Text
        aCell.Offset(, 4).Value = Me.TextBox7.Text
        aCell.Offset(, 5).Value = Me.TextBox8.Text

        MsgBox "Quote Number " & strSearch & " Has Been Updated"
    End If
End With

Exit Sub
End Sub

Private Sub Label1_Click()

End Sub

Private Sub Label6_Click()

End Sub

Private Sub Label8_Click()

End Sub

Private Sub TextBox1_Change()

End Sub

修改后,我可以轻松地更改文本框中的数据并更新信息。

1 个答案:

答案 0 :(得分:0)

本质上,您正在使用“偏移”,因此,如果您的号码在B10中找到,并且您希望C10进入Textbox1,您将使用

Me.Textbox1.Value = aCell.Offset(, 1).value

假设此代码位于表格的后面。