从一个Excel工作簿更新2列到其他工作簿

时间:2015-05-25 05:30:27

标签: excel vba vlookup

我有两本工作表A和B。

Book 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卷的动物栏目的重量和大小。 喜欢。

鹿的体重:28,大小:20本书,然后它应该更新鹿的体重和大小,而不是重量:18和大小:10。

我看到了VLOOKUP功能和一些相关问题,但无法找到它。 请帮帮我。 在此先感谢.. !!!

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

首先打开书B. 让书A关闭 右键单击工作表名称并选择视图代码 复制并粘贴此内容 编辑说明 按绿色播放按钮或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
相关问题