【发布时间】:2020-12-09 09:29:16
【问题描述】:
我正在处理的情况是一个表格,其中第一列是帐号,第五列是金额,第七列是“F”或“P”。帐号与位于第一列中另一个工作簿上的帐号相匹配。如果在表格的第七列(在源工作簿中,有一个“F”,则该值应该被复制、匹配并粘贴到目标工作簿第四列的同一行。如果有一个“ P,' 值应匹配并粘贴到目标工作簿第五列的同一行。代码有效,但无法区分 F 或 P。它将所有值都粘贴到两列中。
Private Sub CommandButton2_Click()
Dim Dic As Object, key As Variant, oCell As Range, i&
Dim w1 As Worksheet, w2 As Worksheet
Dim cell As Range
Dim SrchRng As Range
Set Dic = CreateObject("Scripting.Dictionary")
Set w1 = Workbooks("HF Pricing Template1").Sheets("Tables")
Set w2 = Workbooks("Book1").Sheets("Sheet1")
Set SrchRng = Range("Table3[Price_Type]")
For Each cell In SrchRng
If cell.Value = "P" Then
i = w1.Cells.SpecialCells(xlCellTypeLastCell).Row
For Each oCell In w1.Range("M5:M" & i)
If Not Dic.exists(oCell.Value) Then
Dic.Add oCell.Value, oCell.Offset(, 5).Value
End If
Next
i = w2.Cells.SpecialCells(xlCellTypeLastCell).Row
For Each oCell In w2.Range("A2:A" & i)
For Each key In Dic
If oCell.Value = key Then
oCell.Offset(, 3).Value = Dic(key)
End If
Next
Next
End If
Next cell
For Each cell In SrchRng
If cell.Value = "P" Then
i = w1.Cells.SpecialCells(xlCellTypeLastCell).Row
For Each oCell In w1.Range("M5:M" & i)
If Not Dic.exists(oCell.Value) Then
Dic.Add oCell.Value, oCell.Offset(, 5).Value
End If
Next
i = w2.Cells.SpecialCells(xlCellTypeLastCell).Row
For Each oCell In w2.Range("A2:A" & i)
For Each key In Dic
If oCell.Value = key Then
oCell.Offset(, 4).Value = Dic(key)
End If
Next
Next
End If
Next cell
End Sub
【问题讨论】: