[办公]
编写Excel VBA程序,从B1单元格开始,查找P列,找到相同的内容,将对应行的Q列值填...
我来帮你编写这个Excel VBA程序,它会从B1单元格开始查找P列中的相同内容,并将对应行的Q列值填入J列。
- Sub 查找并填充数据()
- Dim ws As Worksheet
- Dim lastRowB As Long, lastRowP As Long
- Dim i As Long, j As Long
- Dim lookupValue As String
- Dim found As Boolean
-
- ' 设置当前工作表
- Set ws = ActiveSheet
-
- ' 获取B列和P列的最后一行
- lastRowB = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
- lastRowP = ws.Cells(ws.Rows.Count, "P").End(xlUp).Row
-
- ' 从B1开始遍历B列
- For i = 1 To lastRowB
- lookupValue = ws.Cells(i, "B").Value
-
- ' 如果B列单元格为空,跳过
- If lookupValue = "" Then
- ws.Cells(i, "J").Value = ""
- GoTo NextIteration
- End If
-
- found = False
-
- ' 在P列中查找相同的值
- For j = 1 To lastRowP
- If ws.Cells(j, "P").Value = lookupValue Then
- ' 找到匹配项,将Q列对应的值填入J列
- ws.Cells(i, "J").Value = ws.Cells(j, "Q").Value
- found = True
- Exit For
- End If
- Next j
-
- ' 如果没有找到匹配项
- If Not found Then
- ws.Cells(i, "J").Value = "未找到匹配"
- End If
-
- NextIteration:
- Next i
-
- ' 显示完成消息
- MsgBox "数据填充完成!", vbInformation, "操作完成"
- End Sub
复制代码
**使用说明:**
1 按 `Alt + F11` 打开VBA编辑器
2 插入一个新的模块
3 将上面的代码粘贴进去
4 按 `F5` 运行宏,或在Excel中添加一个按钮来调用这个宏
**功能说明:**
- 从B1单元格开始遍历B列的所有数据
- 在P列中查找相同的内容
- 找到匹配项后,将对应行Q列的值填入J列
- 如果B列为空,J列也留空
- 如果没有找到匹配项,J列显示"未找到匹配"
你可以根据需要修改代码中的提示信息或处理逻辑。
|
|
|
|
|
|
|
|