使用userform搜索和更新行中的值

时间:2017-04-13 09:19:24

标签: vba excel-vba search userform excel

我已经为数据输入创建了一个用户表单。我现在想要扩展它以查看已输入的数据,其中可能缺少某些数据,并更新该行中的值。

搜索条件是一个引用号,它位于A列的表中。但是代码返回的是没有找到ID的msg。

Dim searchRange As Range
Dim foundCell As Range
Dim mysearch As String

mysearch = Me.Reference.Value

Set searchRange = ThisWorkbook.Sheets("Master Data").Range("A2").End(xlDown)
Set foundCell = searchRange.Find(what:=mysearch, after:=searchRange.Cells(searchRange.Cells.Count))

If Not foundCell Is Nothing Then
    If foundCell.Offset(0, 1).Value = Me.Reference.Value Then
       foundCell.Offset(0, 8).Value = Me.Merchant.Value
    Else
        MsgBox "Name does not exist."
    End If
Else
    MsgBox "ID does not exist."
End If

1 个答案:

答案 0 :(得分:3)

试试这个,你定义的searchRange只是一个单元格,我认为它不是你想要的。我还指定了一些Find参数,以防万一它们不是你想象的那样。

Sub x()

Dim searchRange As Range
Dim foundCell As Range
Dim mysearch As String

mysearch = Me.Reference.Value

With ThisWorkbook.Sheets("Master Data")
    Set searchRange = .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
End With        

Set foundCell = searchRange.Find(what:=mysearch, Lookat:=xlwhole, MatchCase:=False, SearchFormat:=False)
If Not foundCell Is Nothing Then
     If foundCell.Offset(0, 1).Value = Me.Reference.Value Then
         foundCell.Offset(0, 8).Value = Me.Merchant.Value
     Else
         MsgBox "Name does not exist."
     End If
Else
     MsgBox "ID does not exist."
End If

End Sub