Excel 根据匹配条件复制值
我有两本内容相同的作业本。当项目编号和分区相同时,我将金额值从一张工作簿复制并粘贴到另一张工作簿。必须将金额粘贴到匹配的行中。我面临的问题是,所有金额都被复制,但没有粘贴到相应的匹配项附近 我使用的代码如下:Excel 根据匹配条件复制值,excel,vba,Excel,Vba,我有两本内容相同的作业本。当项目编号和分区相同时,我将金额值从一张工作簿复制并粘贴到另一张工作簿。必须将金额粘贴到匹配的行中。我面临的问题是,所有金额都被复制,但没有粘贴到相应的匹配项附近 我使用的代码如下: ws1PRNum = "E" 'Project Number ws1Div = "I" 'Division ws2PRNum = "E" 'Project Nu
ws1PRNum = "E" 'Project Number
ws1Div = "I" 'Division
ws2PRNum = "E" 'Project Number
ws2Div = "I" 'Division
'Setting first and last row for the columns in both sheets
ws1PRRow = 5 'The row we want to start processing first
ws1EndRow = wsSrc.UsedRange.Rows(wsSrc.UsedRange.Rows.count).Row
ws2PRRow = 5 'The row we want to start search first
ws2EndRow = wsDest.UsedRange.Rows(wsDest.UsedRange.Rows.count).Row
For i = ws1PRRow To ws1EndRow 'first and last row
searchKey = wsSrc.Range(ws1PRNum & i) & wsSrc.Range(ws1Div & i) 'PR line and number is Master Backlog
'if we have a non blank search term then iterate through possible matches
If (searchKey <> "") Then
For j = ws2PRRow To ws2EndRow 'first and last row
foundKey = wsDest.Range(ws2PRNum & j) & wsDest.Range(ws2Div & j) 'PR line and number in PR Report
'Copy result if there is a match between PR number and line in both sheets
If (searchKey = foundKey) Then
'Copying data where the rows match
wsDest.Range("AJ5", "AU1200").Value = wsSrc.Range("AJ5", "AU1200").Value
wsDest.Range("BB5", "BM1200").Value = wsSrc.Range("BB5", "BM1200").Value
wsDest.Range("BT5", "BU1200").Value = wsSrc.Range("BT5", "BU1200").Value
Exit For
End If
Next
End If
Next
项目编号
ws1Div=“I”分部
ws2PRNum=“E”项目编号
ws2Div=“I”分部
'为两个工作表中的列设置第一行和最后一行
WS1PRO=5'我们要首先开始处理的行
ws1EndRow=wsSrc.UsedRange.Rows(wsSrc.UsedRange.Rows.count).Row
ws2prow=5'我们要首先开始搜索的行
ws2EndRow=wsDest.UsedRange.Rows(wsDest.UsedRange.Rows.count).Row
对于i=WS1prow至ws1EndRow“第一行和最后一行”
searchKey=wsSrc.Range(ws1PRNum&i)和wsSrc.Range(ws1Div&i)的PR行和编号为主积压
'如果我们有一个非空的搜索项,则遍历可能的匹配项
如果(搜索键“”),则
对于j=WS2prow到ws2EndRow的第一行和最后一行
foundKey=wsDest.Range(ws2PRNum&j)和wsDest.Range(ws2Div&j)在PR报告中的PR行和编号
'如果两张表中的PR编号和行匹配,则复制结果
如果(searchKey=foundKey),则
'正在复制行匹配的数据
wsDest.Range(“AJ5”、“AU1200”).Value=wsSrc.Range(“AJ5”、“AU1200”).Value
wsDest.Range(“BB5”、“BM1200”).Value=wsSrc.Range(“BB5”、“BM1200”).Value
wsDest.Range(“BT5”、“BU1200”).值=wsSrc.Range(“BT5”、“BU1200”).值
退出
如果结束
下一个
如果结束
下一个
这是导致问题的区域。如图所示,即使在分区和项目编号为空的行中,也会粘贴金额。如果您能回答我的问题,我将不胜感激,因为我不太熟悉VBA。您可以这样做:
wsDest.Range(“AJ”&j,“AU”&j).Value=wsSrc.Range(“AJ”&i,“AU”&i).Value
“等等。。。
或者使用稍微少一点的连接:
wsDest.Rows(j).Range(“AJ1:AU1”).Value=wsSrc.Rows(i).Range(“AJ1:AU1”).Value