やりたいことを実現する方法はたくさんあります。ここに3つの方法があります...
方法 1 (使用.Find
)
あなたもこれを見たいと思うかもしれません。
Option Explicit
Sub Compare()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim Group As Range, Mat As Range, aCell As Range
Dim lRow As Long, i As Long
Dim Ret
Application.ScreenUpdating = False
Ret = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select the file")
If Ret = False Then Exit Sub
Set wb1 = Workbooks.Open(Ret)
Set wb2 = ThisWorkbook
Set ws1 = wb1.Sheets("Sheet1")
Set ws2 = wb2.Sheets("Sheet2")
With ws2
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
Set aCell = ws1.Columns(1).Find(What:=.Range("A" & i).Value, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not aCell Is Nothing Then
.Range("B" & i).Value = aCell.Offset(, 1).Value
End If
Next i
End With
wb1.Close (False)
Application.ScreenUpdating = True
End Sub
方法 2 (使用Loops
)
Option Explicit
Sub Compare()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim Group As Range, Mat As Range
Dim lRowWs1 As Long, lRoWws2 As Long, i As Long, j As Long
Dim Ret
Application.ScreenUpdating = False
Ret = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select the file")
If Ret = False Then Exit Sub
Set wb1 = Workbooks.Open(Ret)
Set wb2 = ThisWorkbook
Set ws1 = wb1.Sheets("Sheet1")
Set ws2 = wb2.Sheets("Sheet38")
With ws2
lRoWws2 = .Range("A" & .Rows.Count).End(xlUp).Row
lRowWs1 = ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row
For i = 1 To lRoWws2
For j = 1 To lRowWs1
If .Range("A" & i).Value = ws1.Range("A" & j).Value Then
.Range("B" & i).Value = ws1.Range("B" & j).Value
Exit For
End If
Next j
Next i
End With
wb1.Close (False)
Application.ScreenUpdating = True
End Sub
方法 3 (Vlookup
コードで数式を使用)
Option Explicit
Sub Compare()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim Group As Range, Mat As Range
Dim lRow As Long
Dim FName As String
Dim Ret
Application.ScreenUpdating = False
Ret = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select the file")
If Ret = False Then Exit Sub
Set wb1 = Workbooks.Open(Ret)
Set wb2 = ThisWorkbook
FName = wb1.Name
Set ws1 = wb1.Sheets("Sheet1")
Set ws2 = wb2.Sheets("Sheet38")
With ws2
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B1:B" & lRow).Formula = "=VLOOKUP(A1,[" & FName & "]Sheet1!$A:$B,2,0)"
.Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
End With
wb1.Close (False)
Application.ScreenUpdating = True
End Sub