VBA - 从行中搜索 retrieve/copy 数据的宏并填充特定的目标单元格。反向数据录入

VBA - Search macro to retrieve/copy data from row and populate specific targeted cells. Reverse data entry

我想反向查找通过表单输入的数据。我有一个按钮可以将数据从表单传输到 table、VBA 代码,如下所示,如果有调整此代码的方法:

Sub data_input()

ws_output = "Shelf Stock Data"

next_row = Sheets(ws_output).Range("A" & Rows.Count).End(xlUp).Offset(1).Row

Sheets(ws_output).Cells(next_row, 1).Value = Range("staff_name").Value
Sheets(ws_output).Cells(next_row, 2).Value = Range("supplier").Value
Sheets(ws_output).Cells(next_row, 3).Value = Range("signed").Value
Sheets(ws_output).Cells(next_row, 4).Value = Range("po_number").Value
Sheets(ws_output).Cells(next_row, 5).Value = Range("roll_length").Value
Sheets(ws_output).Cells(next_row, 6).Value = Range("roll_width").Value
Sheets(ws_output).Cells(next_row, 7).Value = Range("shelf_location").Value
Sheets(ws_output).Cells(next_row, 8).Value = Range("date").Value
Sheets(ws_output).Cells(next_row, 9).Value = Range("in_out").Value
Sheets(ws_output).Cells(next_row, 10).Value = Range("notes_comments").Value
  
MsgBox "Submitted - Please clear the workbook before you save"
  
End Sub

我现在正在尝试检索存储在行中的此信息并重新填充表单字段,以便通过搜索“po_number”来快速编辑股票变动。

最终用户对计算机很不了解,所以一个简单的按钮和搜索栏是最好的解决方案。

数据table可能会有多个相同“po_number”的条目,那么是否可以只显示搜索结果的最新条目?

感谢您提供的任何帮助。

Option Explicit

Sub data_search()

    Dim wb As Workbook, rng As Range
    Dim ws_output As Worksheet, ws_input As Worksheet
    Dim iLastRow As Long, r As Long, po As String

    Set wb = ThisWorkbook
    Set ws_input = wb.Sheets("Input Form")

    ' po to search
    po = Trim(Range("po_number").Value)
    If Len(po) = 0 Then
        MsgBox "Search term empty", vbExclamation
        Exit Sub
    End If

    ' search column D for po
    Set ws_output = wb.Sheets("Shelf Stock Data")
    iLastRow = ws_output.Cells(Rows.Count, "D").End(xlUp).Row
    Set rng = ws_output.Range("D2:D" & iLastRow).Find(po, _
          LookIn:=xlValues, _
          lookat:=xlWhole, _
          SearchDirection:=xlPrevious)

    ' result of search
    If rng Is Nothing Then
        MsgBox po & " not found", vbExclamation
    Else
        r = rng.Row
        With ws_output
            Range("staff_name").Value = .Cells(r, 1).Value
            Range("supplier").Value = .Cells(r, 2).Value
            Range("signed").Value = .Cells(r, 3).Value
            Range("roll_length").Value = .Cells(r, 5).Value
            Range("roll_width").Value = .Cells(r, 6).Value
            Range("shelf_location").Value = .Cells(r, 7).Value
            Range("date").Value = .Cells(r, 8).Value
            Range("in_out").Value = .Cells(r, 9).Value
            Range("notes_comments").Value = .Cells(r, 10).Value
        End With
    End If
  
End Sub