如何在Excel中将每个输入框条目写入第一行?

时间:2014-02-07 07:14:05

标签: vba excel-vba usb barcode-scanner excel

我写了一个Excel宏,它似乎工作正常。它显示一个输入框,一旦我给它输入值。它将该值保存到列C(C1)的第一个单元格中。但是第二次运行宏我希望将它写入C2并将所有数据保存在C列的不同行中,但每次都将其写入C1并导致数据丢失。

Sub DataInput()

    Dim SearchTarget As String
    Dim myRow As Long
    Dim Rng As Range


    Static PrevCell As Range
    Dim FoundCell As Range
    Dim CurCell As Range
    Dim a As String
    Dim Target As Range

    'SearchTarget = "asdf"
    SearchTarget = InputBox("Scan or type product barcode...", "New State Entry")

    If PrevCell Is Nothing Then
        myRow = Selection.Row
        Set PrevCell = Range("C" & myRow)
    End If

    'Set Rng = Range("C:C,E:E") 'Columns for search defined here
    Set Rng = Range("C:C,C:C") 'Columns for search defined here

    With Rng
        Set FoundCell = .Cells.Find(What:=SearchTarget, _
        After:=PrevCell, LookIn:=xlFormulas, LookAt:= _
        xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=True)
    End With

    If FoundCell Is Nothing Then

        MsgBox SearchTarget & " was not found."
        Range("C1").Value = InputBox("code?")
        Range("D1").Value = Now()

    Else

        FoundCell.Activate
        '        If PrevCell.Address = FoundCell.Address Then
        '            MsgBox "there's only one!"
        '        End If

        ActiveCell.Offset(0, 1).Select
        timestamp = Format(Now(), "dd-mmm-yy hh:mm")
        ActiveCell = timestamp
        ActiveCell = Now()

        ActiveCell.Offset(0, 2).Select
        ActiveCell = "T141000"

        ActiveCell.Offset(0, 1).Select

        Set PrevCell = FoundCell

    End If

End Sub

1 个答案:

答案 0 :(得分:0)

这里的问题在于你的if语句 - 你总是将新输入的代码存储在单元格C1中,将日期存储在D1中。您需要动态计算下一个可用的行号并改为使用它。尝试这样的事情:

Public Sub DataInput()

    ...

    If FoundCell Is Nothing Then

        MsgBox SearchTarget & " was not found."

        Dim nextFreeRow As Integer
        nextFreeRow = Range("C" & Rows.Count).End(xlUp).Row + 1

        Range("C" & nextFreeRow).Value = InputBox("code?")
        Range("D" & nextFreeRow).Value = Now()

    Else
        ...
    End If

    ...

End Sub