将 2 列从一个 excel 工作簿更新到另一个工作簿

Updating 2 columns from one excel workbook to other workbook

我有两个工作表 Book A 和 Book B。

书 A 有 3 列

Elements (duck,
elephant,deer,monkey), Weight(20,70,18,25), Size(10,30,10,6)

分别。

B 书也有相同的列 Elements (elephant,deer), Weight (80,28) and size(40,20)

我需要更新书 A 中书 B 的动物列的重量和大小。 像。

鹿在书 B 中有 weight:28 和 size:20。那么它应该更新书 A 中鹿的体重和大小而不是 weight:18 和大小:10。

我看到了 VLOOKUP 函数和一些相关问题,但找不到它。 请帮助我。 提前致谢..!!!

你可以试试这个:

先打开B册 关闭 Book A 右键单击 sheet 名称和 select 查看代码 将其复制并粘贴到 在规定的地方编辑 按绿色播放按钮或 F5

***** 不要忘记在 运行 之前保存文件的备份副本,以防出现任何数据损坏 *****

Sub updateBook()

Dim loop1, loop2 As Long
Dim rows1, rows2 As Integer

Dim Path As String
Path = "Path to Book A"  'edit within the quotes the path to Book A file e.g C:\users\name\BookA.xlsm

Dim openWb As Workbook
Set openWb = Workbooks.Open(Path)

Dim openWs As Worksheet
Set openWs = openWb.Sheets("Sheet Name in Book A")   'edit within the quotes the sheet name of Book A

Dim currentWb As Workbook
Set currentWb = ThisWorkbook

Dim currentWs As Worksheet
Set currentWs = currentWb.Sheets("Sheet Name in Book B")  'edit within the quotes the sheet name of Book B

rows1 = currentWs.UsedRange.Rows.Count
rows2 = openWs.UsedRange.Rows.Count

For loop1 = 1 To rows1 Step 1
    For loop2 = 1 To rows2 Step 1
        If openWs.Cells(loop2, 1).Value = currentWs.Cells(loop1, 1).Value Then
        'check if names match between books
            openWs.Cells(loop2, 2).Value = currentWs.Cells(loop1, 2).Value
            'replaces the old value in 2nd column with new value from Book A
            openWs.Cells(loop2, 3).Value = currentWs.Cells(loop1, 3).Value
            'replaces the old value in 3rd column with new value from Book A
        End If
    Next loop2
Next loop1

Application.DisplayAlerts = False
openWb.Close (True)
'saves and closes book B

End Sub