问题
I am wanting to set up an excel spreadsheet for data entry with a barcode scanner. The barcode scanner sends the barcode then a tab OR an enter key depending how its programmed.
Basically I want to set up an excel sheet that we can scan 6 barcodes for each item, with the scanner tabbing to the next column each time, then when it reaches the 6th column the next tab will make it move to a new line for the next product.
I hope this makes sense. It can be done in MS word... e.g if you create a table with 6 columns and push tab 7 times it will move to the next row. I am wanting to do this in Excel. Thank you
回答1:
The TAB or ENTER keys already trigger the SelectionChange
event.
So, this might be a little tidier way of doing the same thing if you don't for some other reaason need to use the Change
event instead of the SelectionChange
event.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim rngLastColumn As Range
'Note: The {Tab} or {Enter} key triggers selectionChange event.'
' Modify the address of rngLastColumn as needed. It should be one column beyond
' the last column of your inputs, so if input use columns A:F, then it should
' be Range("G:G").
Set rngLastColumn = Range("G:G")
If Not Intersect(Target, rngValidColumns.Columns(7)) Is Nothing Then
'Insert a new row:'
Target.EntireRow.Offset(1, 0).Insert
'Select the first cell in the new row'
cells(Target.Row + 1, 1).Select
End If
End Sub
回答2:
Well... after a lot of experimenting gathering pieces of code from a lot of places and then debugging I ended up with the following VBA macro. Hope it helps! :)
- When
TAB
orENTER
key is pressed theSub Worksheet_Change
will run. - It will check if it's column
F
being left... - If true => insert new row and select first cell
[A]n
wheren
= row number.
VBA macro code
Private Sub Worksheet_Change(ByVal Target As Range)
'Do nothing if more than one cell is changed or content deleted
If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub
'Column F
If Target.Column = "6" Then
'Insert new row bellow
ActiveCell.EntireRow.Offset(1, 0).Insert
'Select first cell of next row just inserted
ActiveSheet.Cells(ActiveCell.Row + 1, 1).Select
End If
End Sub
Private Sub Workbook_Activate()
Application.OnKey "{TAB}", "Worksheet_Change" 'TAB key press
Application.OnKey "~", "Worksheet_Change" 'Keyboard ENTER press
End Sub
Private Sub Workbook_Deactivate()
Application.OnKey "{TAB}"
Application.OnKey "~"
End Sub
回答3:
Maybe I'm missing something on the issue, but if you select your six columns and transform the selection with the "create list" command, then whenever you tab to the last cell of a line you'll automatically going to the next line. Furthermore, if you're at the last line, a new one will be created. IM not sure why you need a macro for that ?
来源:https://stackoverflow.com/questions/16027171/excel-tab-to-new-line-after-certain-amount-of-columns