所以我已經挖掘了幾個小時的答案,我發現了類似的案例,但沒有一個與我正在尋找的完全相同。
希望能得到你的幫助(如果這真的可能的話)。讓我簡短地解釋一下這種做法背后的想法。
我有兩個不同的作業表(作業表 1 和作業表 2),我想將作業表 1 中的 A 列與作業表 2 中的 A 列進行比較。
如果值完全匹配,我想將資料從 sheet2 復制到 sheet1 到匹配值的行中。
我正在處理的資料是敏感日期,因此我創建了一個示例粘貼到此處 - 希望這是可以理解的:

正如您在螢屏上看到的,如果 A 列 (sheet1) 中的值與 B 列 (sheet2) 中的值匹配,則會導致替換 sheet1 中列中的特定資料。
我希望這是可以理解的,并且您將能夠對此案提供幫助。
我怎樣才能解決這個問題?我對 VBA/宏完全陌生,很想向你們學習。
uj5u.com熱心網友回復:
使用字典物件將 sheet2 上的標題名稱與 sheet1 上的標題名稱匹配。
更新 - 添加修剪以將數字轉換為字串
Option Explicit
Sub Update()
Const ROW_HEADER = 1
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lastrow As Long, lastcol As Long, r As Long, c As Long
Dim arID, id As String, n As Long, m As Variant
Dim dictCol As Object, k As String
Set dictCol = CreateObject("Scripting.Dictionary")
' profile sheet2 columns
Set ws2 = ThisWorkbook.Sheets("Sheet2")
With ws2
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
arID = .Range("A1:A" & lastrow).Value2 ' range of iDs
lastcol = .Cells(ROW_HEADER, .Columns.Count).End(xlToLeft).Column
For c = 1 To lastcol
k = Trim(.Cells(ROW_HEADER, c)) ' header text
If dictCol.exists(k) Then
MsgBox "Duplicate header '" & k & "' at column " & c, vbCritical
Exit Sub
ElseIf Len(k) > 0 Then
dictCol(k) = c ' column number
End If
Next
End With
For r = 1 To UBound(arID): arID(r, 1) = Trim(arID(r, 1)): Next
MsgBox dictCol.Count & " columns found on sheet " & ws2.Name, vbInformation
' update sheet1
Set ws1 = ThisWorkbook.Sheets("Sheet1")
With ws1
lastcol = .Cells(ROW_HEADER, .Columns.Count).End(xlToLeft).Column
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For r = 2 To lastrow
id = Trim(.Cells(r, "A"))
' locate row on sheet2
m = Application.Match(id, arID, 0)
If Not IsError(m) Then
' scan columns
For c = 2 To lastcol
k = trim(.Cells(ROW_HEADER, c))
' find col on sheet2
If dictCol.exists(k) Then
' update if different
If .Cells(r, c) <> ws2.Cells(m, dictCol(k)) Then
.Cells(r, c).Interior.Color = RGB(255, 255, 0) ' mark yellow for checking
.Cells(r, c) = ws2.Cells(m, dictCol(k))
n = n 1
End If
Else
MsgBox "Column " & k & " not found", vbCritical
Exit Sub
End If
Next
Else
Debug.Print id, m
End If
Next
End With
' end
MsgBox lastrow - 1 & " rows scanned " & vbLf & _
n & " cells updated", vbInformation
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/361417.html
