|
楼主 |
发表于 2023-4-27 00:51
|
显示全部楼层
这是用AI写出来的代码,声明完变量还是不行
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 rowFound As Boolean '是否找到了匹配的行
'初始化变量
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 wb = Workbooks.Open(Path)
If wb Is Nothing Then GoTo endMacro
Set ws1 = Worksheets("YT-8出车及过表")
Set ws2 = Worksheets("部属车-YT-8")
Set ws3 = Worksheets("企业车-YT-8")
'获取导入文件中工作表"第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(what:=carNum, LookIn:=xlValues)
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(what:=carNum, LookIn:=xlValues)
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
Next
'显示执行结果
Dim msg As String
msg = "本次出车共导入" & outCount & "辆,实际成功出车" & (deptCarCount + entCarCount) & "辆(部属车" & deptCarCount & "辆,企业车" & entCarCount & "辆),未查找到车号" & notFoundCount
MsgBox msg
endMacro:
End Sub |
|