Excel条码扫描表出现VBA Overflow Error 6的解决求助
问题解决步骤
1. 解决Overflow 6错误
直接读取单元格的文本内容,避免数值转换触发溢出:
barcode = Worksheets("Sheet1").Cells(2, 2).Text
或者提前将B2单元格设置为文本格式:选中B2单元格,右键选择「设置单元格格式」→「数字」→「文本」,让扫描的条码直接以文本形式存储,彻底规避数值转换问题。
2. 解决单元格显示####的问题
- 双击B列列标右侧的分隔线,自动适配内容宽度;
- 或者将B列整列设置为文本格式,避免条码被识别为数值,导致列宽不足时显示####。
3. 修正代码中的语法与逻辑错误
原代码存在多处语法错误和不规范写法,以下是修正后的完整代码:
Sub inout() Dim barcode As String Dim rng As Range Dim rownumber As Long Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") ' 获取条码文本,避免数值转换溢出 barcode = ws.Cells(2, 2).Text If barcode <> "" Then ' 修正Find语句的括号闭合问题 Set rng = ws.Columns("A:A").Find(What:=barcode, _ LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If rng Is Nothing Then again: ' 更可靠地定位A列下一个空行 rownumber = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1 ws.Cells(rownumber, "A").Value = barcode ' 写入进入时间,移除冗余的Select操作 With ws.Cells(rownumber, "B") .Value = Now .NumberFormat = "m/d/yyyy h:mm AM/PM" End With ws.Cells(2, 2).ClearContents Else rownumber = rng.Row ' 修正Interior拼写错误,优化单元格操作 With ws.Cells(rownumber, "C") .Interior.ColorIndex = 4 ' 修正GoTo语句的语法问题 If .Value <> "" Then GoTo again .Value = Now .NumberFormat = "m/d/yyyy h:mm AM/PM" End With ws.Cells(2, 2).ClearContents End If End If End Sub
代码修正说明:
- 增加工作表变量
ws,减少重复调用,提升执行效率; - 用
.Text获取条码内容,彻底解决溢出问题; - 替换
Find("")为End(xlUp).Row + 1,避免空单元格查找的不确定性; - 移除所有
Select和ActiveCell操作,直接引用单元格,规避工作表切换导致的错误; - 修正
Interiot拼写错误、NumberFormat赋值符号错误、GoTo语句换行问题; - 用
Now替代Date & " " & Time,写法更简洁高效; - 用
ClearContents替代空字符串赋值,操作更规范。
内容的提问来源于stack exchange,提问作者Appalachia Paranormal
相关产品推荐
相关产品推荐

