Excel文件中有两个工作表:来料明细和生产需求,要求用VBA编程判断来料明细中的物料到厂日期和数量能否满足生产需求,并在相应的列中回复,具体要求如下:
1.通过生产需求工作表中的缺料料号在来料明细工作表中进行查找相应的来料日期、来料数量。
2.将上一步中搜索的结果在生产需求工作表中进行反馈:E列输入到厂日期、F列可分配数量、若能满足生产则在G列输入“”OK“”,否则输入“”NO“”
3.若来料明细中未查到料号,则在生产需求工作表中E列~G列输入“”待确认“”
以下是实现该需求的VBA代码解决方案,分为核心逻辑和操作步骤:
核心代码实现
Sub CheckMaterialAvailability()
Dim wsIncoming As Worksheet
Dim wsProduction As Worksheet
Dim lastRowProd As Long
Dim lastRowInc As Long
Dim i As Long, j As Long
Dim found As Boolean
Set wsIncoming = Worksheets("来料明细")
Set wsProduction = Worksheets("生产需求")
lastRowProd = wsProduction.Cells(wsProduction.Rows.Count, "B").End(xlUp).Row
lastRowInc = wsIncoming.Cells(wsIncoming.Rows.Count, "B").End(xlUp).Row
For i = 2 To lastRowProd
found = False
For j = 2 To lastRowInc
If wsProduction.Cells(i, "B").Value = wsIncoming.Cells(j, "B").Value Then
found = True
wsProduction.Cells(i, "E").Value = wsIncoming.Cells(j, "C").Value
wsProduction.Cells(i, "F").Value = wsIncoming.Cells(j, "D").Value
If wsIncoming.Cells(j, "D").Value >= wsProduction.Cells(i, "D").Value Then
wsProduction.Cells(i, "G").Value = "OK"
Else
wsProduction.Cells(i, "G").Value = "NO"
End If
Exit For
End If
Next j
If Not found Then
wsProduction.Cells(i, "E").Value = "待确认"
wsProduction.Cells(i, "F").Value = "待确认"
wsProduction.Cells(i, "G").Value = "待确认"
End If
Next i
MsgBox "物料检查完成", vbInformation
End Sub
代码说明
- 假设数据从第2行开始(第1行为标题行)
- 料号存储在B列(来料明细和生产需求工作表相同)
- 来料日期在来料明细的C列,来料数量在D列
- 生产需求数量在生产需求的D列
使用方法
- 打开Excel文件,按
Alt+F11打开VBA编辑器 - 在左侧工程资源管理器中右键点击VBAProject
- 选择"插入"→"模块"
- 将上述代码粘贴到新建的模块中
- 关闭VBA编辑器,按
Alt+F8打开宏对话框 - 选择
CheckMaterialAvailability宏并运行
注意事项
- 确保两个工作表的名称与代码中的名称完全一致
- 料号列必须是文本格式,避免因数字格式差异导致匹配失败
- 生产需求数量应为数值格式
- 代码运行前建议备份原始数据
如需调整列位置或其他参数,只需修改代码中对应的列字母即可。例如将来料日期列从C列改为E列,则将代码中的wsIncoming.Cells(j, "C")改为wsIncoming.Cells(j, "E")。

611

被折叠的 条评论
为什么被折叠?



