当工作簿里"录入正表"表的A列录入值时,自动匹配工作簿里"匹配项"表A列唯一值。在通过"匹配项"表标题与"录入正表"表标题名字完全一致情况下把"匹配项"表A列唯一值的同行其他值自动填入到"录入正表"里面去的VBA代码
时间: 2023-09-10 20:04:51 浏览: 129
xh.rar_Excel VBA_VBA 自动匹配_excel 匹配_excel查找_vba 匹配
以下是一个基于描述的 VBA 代码示例,可以实现你所描述的自动匹配和填充操作。请根据实际情况进行适当的调整和修改。
```
Sub MatchAndFill()
Dim mainSheet As Worksheet
Set mainSheet = ThisWorkbook.Sheets("录入正表")
Dim matchSheet As Worksheet
Set matchSheet = ThisWorkbook.Sheets("匹配项")
Dim mainCol As Range
Set mainCol = mainSheet.Range("A:A")
Dim matchCol As Range
Set matchCol = matchSheet.Range("A:A")
Dim mainLastRow As Long
mainLastRow = mainSheet.Cells(mainSheet.Rows.Count, "A").End(xlUp).Row
Dim matchLastRow As Long
matchLastRow = matchSheet.Cells(matchSheet.Rows.Count, "A").End(xlUp).Row
Dim matchDict As Object
Set matchDict = CreateObject("Scripting.Dictionary")
Dim i As Long
For i = 2 To matchLastRow
Dim matchValue As String
matchValue = matchSheet.Cells(i, 1).Value
If Not matchDict.Exists(matchValue) Then
matchDict.Add matchValue, i
End If
Next i
Dim j As Long
For j = 2 To mainLastRow
Dim mainValue As String
mainValue = mainSheet.Cells(j, 1).Value
If matchDict.Exists(mainValue) Then
Dim matchRow As Long
matchRow = matchDict(mainValue)
Dim mainHeaders As Range
Set mainHeaders = mainSheet.Range("1:1")
Dim matchHeaders As Range
Set matchHeaders = matchSheet.Range("1:1")
For Each mainHeader In mainHeaders.Cells
Dim matchHeader As Range
Set matchHeader = matchHeaders.Find(mainHeader.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not matchHeader Is Nothing Then
Dim mainCell As Range
Set mainCell = mainSheet.Cells(j, mainHeader.Column)
Dim matchCell As Range
Set matchCell = matchSheet.Cells(matchRow, matchHeader.Column)
mainCell.Value = matchCell.Value
End If
Next mainHeader
End If
Next j
End Sub
```
这段代码的基本思路是:
- 获取录入正表和匹配项表的相关信息,包括工作表对象、列对象、最后行数等;
- 构建匹配项表的唯一值到行号的字典,便于后续查找;
- 遍历录入正表的每一行,如果能在匹配项表中找到对应唯一值,则遍历录入正表和匹配项表的标题行,找到对应的标题名字完全一致的列,然后将匹配项表的同行其他值自动填入到录入正表相应的单元格中。
请在使用前备份数据,并根据实际情况进行适当的修改和测试。
阅读全文