在列中查找值,然后更改同一行其他位置的值

Find a value within a column, then change a value elsewhere on the same row

我正在使用 Excel "database" 来跟踪项目的生产。在某些情况下,人们会多次扫描一个项目,这会导致在发送给客户时出现问题。

我有一个警告弹出窗口,以防止人们多次扫描一个项目,除非处理返工。如果该项目存在于 "database" 中,则存在一个带有 vbYesNo 按钮的 MsgBox。如果人们点击 "Yes",那就是返工。如果人们点击 "No",这是一个错误并且他们退出了子。

我需要一种方法来处理返工并让它更改与原始项目相同行中的单元格的值。

这是我目前的代码。

Private Sub gbatchd_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) 'Check DB for duplicate value

Set depo = dbgrids.Sheets("Deposition")
Set found = depo.Columns("A").Find(what:=valuetofind, LookIn:=xlValues, lookat:=xlWhole)

valuetofind = gbatchd.Text
FR = depo.Range("A" & Rows.Count).End(xlUp).Row

If KeyCode = 13 Then
    For i = 1 To FR
        If gbatch.Cells(i, 1).Value = valuetofind Then
            MsgBox "This batch has already been deposited!" & vbCrLf & "Rework?", vbYesNo, "Rework?"
            If answer = vbNo Then
                Exit Sub
            Else
                depo.Cells(found.Row, 5).Value = "Rework"
            End If
        End If
    Next
End If
End Sub

撇开对解决方案架构的任何批评,您的代码缺少的是对 answer 变量的赋值:

answer = MsgBox("This batch has already been deposited!" & vbCrLf & "Rework?", vbYesNo, "Rework?")

使用 Option Explicit 并使用适当的类型声明变量 (check out this article)。

您的代码的清理版本可能如下所示:

Option Explicit 'At the very top of your module.

'... Other code ...

Private Sub gbatchd_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) 'Check DB for duplicate value
    Dim wsDepo As Excel.Worksheet
    Dim rngFound As Excel.Range
    Dim sValueToFind As String
    Dim answer As VbMsgBoxResult

    If KeyCode = KeyCodeConstants.vbKeyReturn Then
        'Barcode reader has sent the Enter (Return) key.
        'Attempt to find the value.
        sValueToFind = Trim(gbatchd.Text)
        Set wsDepo = dbgrids.Worksheets("Deposition")
        Set rngFound = wsDepo.Columns(1).Find(What:=sValueToFind, LookIn:=xlValues, LookAt:=xlWhole)

        If Not rngFound Is Nothing Then
            'Value was found. Ask whether it is a rework.
            answer = MsgBox("This batch has already been deposited!" & vbCrLf & "Rework?", vbYesNo, "Rework?")
            If answer = VbMsgBoxResult.vbYes Then
                wsDepo.Cells(rngFound.Row, 5).Value = "Rework"
            End If
        End If

        'Cleanup.
        Set rngFound = Nothing
        Set wsDepo = Nothing
    End If
End Sub