|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
本帖最后由 义重情深 于 2023-4-30 01:41 编辑
VBA效果为:表1、2、3在同一工作簿,在表1输入原始数据,点击宏按钮导入另一个文件的工作表表4,在表2或表3中查找是否有与表4相同的号码,如果有,则在表2或表3有相同号码的那一行输入表1上指定的数据。
我尝试过只读模式点是、点否、另存为、甚至另存为以后把导入的工作表单元格全部解除保护也不行
Sub 整列出车()
'声明变量
Dim wb As Workbook
Dim ws1 As Worksheet 'YT-8出车及过表
Dim ws2 As Worksheet '部属车-YT-8
Dim ws3 As Worksheet '企业车-YT-8
Dim lastRow As Long '导入文件中工作表"第1页"的最后一行
Dim ws As Worksheet
Dim i As Long '循环计数器
Dim outCount As Long '应出车辆数
Dim carCount As Long '出车辆数
Dim deptCarCount As Long '部属车成功出车辆数
Dim entCarCount As Long '企业车成功出车辆数
Dim notFoundCount As Long '未查找到车号的数量
Dim carNum As String '导入文件中工作表"第1页"中的车号
Dim path As String
Dim rowFound As Boolean '是否找到了匹配的行
Dim rngFound As Range
'初始化变量
outCount = 0
carCount = 0
deptCarCount = 0
entCarCount = 0
notFoundCount = 0
rowFound = False
'调用文件选取器选择工作簿
path = Application.GetOpenFilename("Excel文件(*.xls;*.xlsx),*.xls;*.xlsx")
If path = "" Then
MsgBox "请选择要导入数据文件!"
Exit Sub
End If
Set ws1 = ThisWorkbook.Worksheets("YT-8出车及过表")
Set ws2 = ThisWorkbook.Worksheets("部属车-YT-8")
Set ws3 = ThisWorkbook.Worksheets("企业车-YT-8")
Set wb = Workbooks.Open(path)
If wb Is Nothing Then GoTo endMacro
'获取导入文件中工作表"第1页"的最后一行
Set ws = wb.Worksheets("第1页")
With ws
lastRow = .Cells(.Rows.Count, 4).End(xlUp).Row
End With
'循环查找导入文件中工作表"第1页"中的每一行
For i = 16 To lastRow
carNum = wb.Worksheets("第1页").Cells(i, 4).Value '获取车号
'在部属车表中查找该车号,若找到则将信息填入
Set rngFound = ws2.Range("D:D").Find(carNum)
If Not rngFound Is Nothing Then
deptCarCount = deptCarCount + 1
ws2.Cells(rngFound.Row, 4) = ws1.Cells(2, 3).Value '发出车次
ws2.Cells(rngFound.Row, 5) = ws1.Cells(2, 4).Value '发出日期
ws2.Cells(rngFound.Row, 6) = ws1.Cells(2, 5).Value '发出时间
rowFound = True
End If
'在企业车表中查找该车号,若找到则将信息填入
Set rngFound = ws3.Range("D:D").Find(carNum)
If Not rngFound Is Nothing Then
entCarCount = entCarCount + 1
ws3.Cells(rngFound.Row, 4) = ws1.Cells(2, 3).Value
ws3.Cells(rngFound.Row, 5) = ws1.Cells(2, 4).Value
ws3.Cells(rngFound.Row, 6) = ws1.Cells(2, 5).Value
rowFound = True
End If
'如果未找到,则未查找到车号数量+1
If rowFound = False Then notFoundCount = notFoundCount + 1
rowFound = False '重置行查找状态
Next
'显示执行结果
Dim msg As String
msg = "本次出车共导入" & outCount & "辆,实际成功出车" & (deptCarCount + entCarCount) & "辆(部属车" & deptCarCount & "辆,企业车" & entCarCount & "辆),未查找到车号" & notFoundCount
MsgBox msg
endMacro:
End Sub
|
|