vba - 使用另一个电子表格替换 Excel 数据

标签 vba excel

我有两个 Excel 电子表格,一个包含不同人的数据,而另一个更多的是索引。

“索引”电子表格的布局如下(例如);

      A       B
1 [person:][pID: ]
2 [Mark   ][1    ]
3 [James  ][2    ]
4 [John   ][3    ]
5 [David  ][4    ]
n [ ...   ][n    ]

“数据”电子表格的布局如下(例如);
      A
1 [pID:   ][ ...
2 [David  ][ ...
3 [David  ][ ...
4 [David  ][ ...
5 [James  ][ ...
6 [Mark   ][ ...
7 [David  ][ ...
n [ ...   ][ ...

我想做的是将“数据”电子表格中的 A 列替换为“索引”电子表格的相应索引,可能使用 VBA。

结果将是这样的;
      A
1 [pID:   ][ ...
2 [4      ][ ...
3 [4      ][ ...
4 [4      ][ ...
5 [2      ][ ...
6 [1      ][ ...
7 [4      ][ ...
n [ ...   ][ ...

我见过一些使用 switch 语句的静态方法,但我真的很希望能够从另一个电子表格中导入数据。
我试图不诉诸复制粘贴和“全部替换”。

谢谢!

最佳答案

尝试这个:

Sub HTH()

    With Sheets("Data")
        .Columns(2).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        .Cells(1, "B").Value = .Cells(1, "A").Value
        With .Range("A2", .Cells(Rows.Count, "A").End(xlUp)).Offset(, 1)
            .Formula = "=VLOOKUP(A2,Index!A:B,2,FALSE)"
            .Value = .Value
        End With
        .Columns(1).Delete
    End With

End Sub

解释:
Sub HTH()

    With Sheets("Data")
        '// Insert a new column with same format
        .Columns(2).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        '// Copy the header
        .Cells(1, "B").Value = .Cells(1, "A").Value
        '//  Work with the used range of column A 
        With .Range("A2", .Cells(Rows.Count, "A").End(xlUp)).Offset(, 1)
            '// Use a formula to replace the names with corresponding values
            .Formula = "=VLOOKUP(A2,Index!A:B,2,FALSE)"
            '// Replace formula with value
            .Value = .Value
        End With
        '//  Delete the old column
        .Columns(1).Delete
    End With

End Sub

注意:

就个人而言,我会保留原始数据表,并使用一个演示表,该表查找数据表和索引表,并以您想要的方式呈现。然后你不一定需要代码,如果你仍然想使用代码,那么代码会简单得多。您将需要添加代码来关闭屏幕更新并使用错误处理等。

ja72 解决方案的替代方案:
Sub HTH()
    Dim vNames As Variant, vResult As Variant
    Dim lLoop As Long

    vNames = Sheets("Index").UsedRange.Columns(1).Resize(, 2).Value2
    vResult = Sheets("Data").UsedRange.Columns(1).Value2

    With CreateObject("Scripting.Dictionary")
        For lLoop = 2 To UBound(vNames, 1)
            .Add vNames(lLoop, 1), vNames(lLoop, 2)
        Next lLoop

        For lLoop = 2 To UBound(vResult, 1)
            vResult(lLoop, 1) = .Item(vResult(lLoop, 1))
        Next lLoop

        Sheets("Data").Range("A1").Resize(UBound(vResult, 1), 1).Value = vResult
    End With

End Sub

悄悄地相信它也更快;)

关于vba - 使用另一个电子表格替换 Excel 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9283972/

相关文章:

excel - 在 Excel VBA 工作簿的立即窗口中执行多行

vba - 在用户窗体中使用 TextBox 捕获单元格值

excel - 通过vba计算包裹单元格中的行数

java - apache poi 查找工作表中的行数

Excel显示当月第n天

excel - 如何防止添加重复单元格

vba - Excel 使用表格 : How to hide application but have icon in the taskbar

vba - 比较excel中的两个单元格然后返回行

vba - 需要为 vba 中的文本框值简化 vlookup 命令

excel - 合并两个查询而不在 Power Query 中重复行