如何解决VBA-将一个工作表中的两列与另一工作表中的两列进行比较
将一个工作表中的两列与另一工作表中的两列进行比较,并从其他一些具有匹配列的列中获取相应的值。
我的第一张纸上有一个唯一的ID和行ID。我在第二张工作表中以随机顺序具有相同的唯一ID和行ID。我想将第一张纸中的唯一ID和行ID匹配到第二张纸。如果唯一ID和行ID都匹配,则第二张纸上有一些日期可以复制到第一张纸上。只要有匹配项,就应从第二张工作表中复制相应的日期,并将其粘贴到匹配的唯一ID和行ID旁边的第一张工作表上。
由于机密文件,我无法上传文件。
我不擅长VBA,非常感谢您解决此问题。
解决方法
非VBA方法
如果可以的话,我倾向于避免使用VBA-因此,如果这不需要自动化并且可以在工作表中添加列,那么最简单的解决方案就是根本不使用VBA。
在两个电子表格中插入一个新列,这是唯一ID和行ID串联在一起的键,然后只需使用vlookup取回值即可。
- 如果您不希望它保持动态链接,请复制并粘贴值以摆脱公式。
- 如果有时ID和行不匹配,只需将vloopup包装到IFERROR函数中,以在不匹配时使用默认值(例如空白)
第1张纸
// App compat and UI things
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.core:core-ktx:1.3.1'`enter code here`
implementation 'androidx.preference:preference:1.1.1'
第2张纸
ID line +Key+ Pseudo formula
X 13 X13 vlookup X13 in Key column of sheet 2
Y 27 Y27 vlookup Y27 in Key column of sheet 2
+ Key + =要插入的新字段,只是= ID和行
,VBA方法
以下是获取值的非常简单的方法。我可以肯定还有很多其他更有效的方法,但是如果这种方法太慢,我只会打扰他们。
要使用-根据评论配置前几个设置,希望您走了!
Sub RetrieveValues()
Set ws1 = Sheets("Sheet1") 'Sheet we are going to copy results into
Set ws2 = Sheets("Sheet2") 'Sheet we are going to copy results from
'Identify the columns to use in the sheet we are copying into
ws1UniqueIDCol = "B" 'Is the column with the first part of our lookup key - the unique id
ws1LineIdCol = "C" 'Is the column with the second part of our lookup key - the line id
ws1ValToWriteCol = "D" 'Is the column we want to put the found value into
ws1StartRow = 3 'The row we want to start processing first,we can calc the last row automatically
ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.Count).Row
'Identify the columns to use in the sheet we are copying from
ws2UniqueIDCol = "B" 'Is the column with the first part of our lookup key - the unique id
ws2LineIdCol = "C" 'Is the column with the second part of our lookup key - the line id
ws2ValToCopyCol = "D" 'Is the column we want to copy the value from
ws2StartRow = 3 'The row we want to start search first,we can calc the last row automatically
ws2EndRow = ws2.UsedRange.Rows(ws2.UsedRange.Rows.Count).Row
'iterate through search terms
For i = ws1StartRow To ws1EndRow '
searchKey = ws1.Range(ws1UniqueIDCol & i) & ws1.Range(ws1LineIdCol & i)
'if we have a non blank search term then iterate through possible matches
If (searchKey <> "") Then
For j = ws2StartRow To ws2EndRow
foundKey = ws2.Range(ws2UniqueIDCol & j) & ws2.Range(ws2LineIdCol & j)
'if we have a match then copy the result and end this search (so we will take the first match found only)
If (searchKey = foundKey) Then
ws1.Range(ws1ValToWriteCol & i).Value2 = ws2.Range(ws2ValToCopyCol & j).Value2
Exit For
End If
Next
End If
Next
End Sub