[技巧] Excel表查找复制其他单元格内容到本文件中单元格

JUMU实名认证 发表于 2025-08-22 17:23 | 显示全部楼层 | 复制链接分享      上一主题  翻页  下一主题
从当前sheet中H列第2行单元格开始,在文件“C:\11.xlsx”中A列依次搜索是否字符串相同,如果相同,那么复制文件“C:\11.xlsx”中所在行B列单元格内容到当前Excel文件M列对应行的单元格。
该程序验证可以使用。
  1. Sub CopyDataFromExternalWorkbook()
  2.     Dim wbSource As Workbook
  3.     Dim wsSource As Worksheet
  4.     Dim wsCurrent As Worksheet
  5.     Dim lastRowCurrent As Long
  6.     Dim lastRowSource As Long
  7.     Dim i As Long, j As Long
  8.     Dim found As Range
  9.     Dim sourceFilePath As String
  10.    
  11.     sourceFilePath = "C:\11.xlsx"     ' 目标文件路径
  12.     Set wsCurrent = ThisWorkbook.ActiveSheet
  13.    
  14.     ' 打开目标工作簿,若已打开则直接设置
  15.     On Error Resume Next
  16.     Set wbSource = Workbooks("11.XLSX")  ' 目标文件名
  17.     On Error GoTo 0
  18.     If wbSource Is Nothing Then
  19.         Set wbSource = Workbooks.Open(sourceFilePath)
  20.     End If
  21.     Set wsSource = wbSource.Sheets(1) ' 假设是第一个sheet
  22.    
  23.     lastRowCurrent = wsCurrent.Cells(wsCurrent.Rows.Count, "H").End(xlUp).Row   ' 当前文件列H
  24.     lastRowSource = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row   ' 待搜索的文件列A
  25.    
  26.     ' 建议为了效率,将待搜索的目标表A列内容加载到字典中
  27.     Dim dict As Object
  28.     Set dict = CreateObject("Scripting.Dictionary")
  29.     Dim key As String
  30.     For j = 2 To lastRowSource
  31.         key = Trim(wsSource.Cells(j, "A").Value)
  32.         If Len(key) > 0 Then
  33.             dict(key) = j
  34.         End If
  35.     Next j
  36.    
  37.     Dim currentVal As String
  38.     Dim sourceRow As Long
  39.     For i = 2 To lastRowCurrent     ' 从第二行开始
  40.         currentVal = Trim(wsCurrent.Cells(i, "H").Value)      ' 当前文件列H
  41.         If dict.Exists(currentVal) Then
  42.             sourceRow = dict(currentVal)
  43.             wsCurrent.Cells(i, "M").Value = wsSource.Cells(sourceRow, "B").Value     ' B列内容写到M列
  44.             
  45.         End If
  46.     Next i
  47.    
  48.     ' 关闭目标工作簿(可选),如果不想保存改动
  49.     wbSource.Close SaveChanges:=False
  50.     MsgBox "完成数据复制!"
  51. End Sub
复制代码


  距米网  

找到您想要的设计

工程师、学生在线交流学习平台
关注我们

手机版- 距米网 |苏公网安备32041102000587号

©2017-2025 苏ICP备18040927号-1