VBA如何将Userform文本框值匹配填入电子表格对应列
修正后可直接使用的完整代码
Sub Submit() ' 声明变量 Dim sh As Worksheet Dim targetRow As Long, opCol As Long, i As Long Dim opValue As String, idValue As String Dim isExist As Boolean ' 基础校验:必填项不能为空 If Trim(ScanForm.OperationBox.Value) = "" Or Trim(ScanForm.IDbox.Value) = "" Then MsgBox "工序编号和员工ID不能为空", vbExclamation Exit Sub End If opValue = Trim(ScanForm.OperationBox.Value) idValue = Trim(ScanForm.IDbox.Value) Set sh = ThisWorkbook.Sheets("Database") ' 第一步:找到工序对应的列号(匹配第一行的表头,后续新增工序无需改代码) opCol = 0 For i = 2 To sh.UsedRange.Columns.Count ' 从第2列开始找,第1列是工单号 If sh.Cells(1, i).Value = opValue Then opCol = i Exit For End If Next i ' 如果没找到对应工序列提示错误 If opCol = 0 Then MsgBox "未找到对应的工序列,请检查表头配置", vbCritical Exit Sub End If ' 第二步:查找是否已有当前工单号的行 isExist = False For targetRow = 2 To sh.Cells(sh.Rows.Count, "A").End(xlUp).Row ' 从第2行开始遍历,第1行是表头 If sh.Cells(targetRow, "A").Value = Trim(ScanForm.JobBox.Value) Then ' 找到已有工单号,直接填对应工序的员工ID sh.Cells(targetRow, opCol).Value = idValue isExist = True Exit For End If Next targetRow ' 第三步:如果没有找到已有工单号,新增一行写入所有数据 If Not isExist Then targetRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row + 1 sh.Cells(targetRow, 1).Value = Trim(ScanForm.JobBox.Value) sh.Cells(targetRow, opCol).Value = idValue sh.Cells(targetRow, 5).Value = Trim(ScanForm.PartBox.Value) sh.Cells(targetRow, 6).Value = Val(Trim(ScanForm.QtyBox.Value)) sh.Cells(targetRow, 7).Value = Format(Now(), "DD-MM-YY HH:MM") End If ' 第四步:刷新Listbox显示最新数据,此处ListBox1请替换为你实际的Listbox控件名称 With ScanForm.ListBox1 .RowSource = "" .RowSource = "Database!A2:G" & sh.Cells(sh.Rows.Count, "A").End(xlUp).Row End With ' 可选:提交后清空表单内容方便下次扫描 ScanForm.OperationBox.Value = "" ScanForm.IDbox.Value = "" ScanForm.JobBox.Value = "" ScanForm.PartBox.Value = "" ScanForm.QtyBox.Value = "" ScanForm.OperationBox.SetFocus ' 光标自动定位到工序输入框,适配连续扫描场景 End Sub
关键逻辑说明
- 自动匹配工序列:无需硬编码判断固定单元格的值,后续Database表新增工序列仅需修改第一行表头即可自动适配
- 重复工单校验:同一工单号不会重复新增行,仅更新对应工序的员工ID
- 前置空值校验:避免无效空数据写入表格
- 自动刷新列表:提交后Listbox实时显示最新的数据库内容
- 适配扫描场景:提交后自动清空表单、光标回到工序输入框,无需手动操作即可连续扫描
内容的提问来源于stack exchange,提问作者LiloK
相关产品推荐
相关产品推荐

