vba - 使用公共(public)列合并两个 Excel 文件

标签 vba excel

我有两张 Excel 工作表。我必须将两者合并,以便其中一个的值与另一个匹配。例如。

The first excel,    the 2nd excel

1  t                 1   tes1
2  5                 3   tes3
3  t                 4   tes4
4  g

请注意,在第二个 Excel 的第一列中,缺少 2,因此我希望第一个 Excel 看起来像这样,

1 tes1 t
2      5 
3 tes3 t
4 tes4 g

我是卓越新手。对此的任何帮助将不胜感激。

最佳答案

Sub left_join()
Dim res As Variant
Dim i As Long, lastUsedRowSh1 As Long, lastUsedRowSh2 As Long
Dim cell As Range
Sheets(3).Cells.ClearContents
Sheets(1).Range("a:b").Copy Destination:=Sheets(3).Range("a1")
Sheets(3).Columns(2).Insert Shift:=xlToRight
lastUsedRowSh1 = Sheets(1).Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
lastUsedRowSh2 = Sheets(2).Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
i = 1
For Each cell In Sheets(1).Range("a1:a" & lastUsedRowSh1)
    On Error Resume Next
    res = Application.WorksheetFunction.VLookup(cell.Value, Sheets(2).Range("a1:b" & lastUsedRowSh2), 2, 0)
        If Err.Number = 0 Then
            Sheets(3).Range("b" & i).Value = res
            i = i + 1
        Else
            i = i + 1
        End If
Next cell
End Sub

您甚至可以使用简单的公式来求解。

福里奥1

A   B
1   t
2   5
3   t
4   g

Folio2

A   B
1   tes1
3   tes3
4   tes4

Folio3

将 Foglio1 的内容复制到 Foglio3 中,然后运行此公式

=IF(ISERROR(VLOOKUP(Foglio1!A1,Foglio2!$A$1:$B$3,2,0))=TRUE,"",VLOOKUP(Foglio1!A1,Foglio2!$A$1:$B$3,2,0))

并将其向下拖动。问候。

enter image description here

关于vba - 使用公共(public)列合并两个 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8458724/

相关文章:

excel - 在 VBA 上另存为 PDF 文件返回 "Document not saved"错误

excel - 返回字符串中第 N 个字符之后的字符

ms-access - MS Access 多选组合框 选择全部/无

vb.net - 使用命令行将 *.xls 或 *.xlsx 文件转换为管道分隔的 .csv 文件

php - 用PHP读写excel文件

excel - 显示来自多个工作表的数据的单个 Excel 图表

vba - 在不使用剪贴板的情况下将注释从一个工作表转移到另一个工作表

javascript - 将 HTML 文档的 javascript 部分中的字段提取到表中?地理坐标

excel - 如何将所有这些代码放在一起以作为一个模块运行?

VBA 无法发送日历约会