[办公] 复制F列内容到当前F列对应单元格,复制G列内容到当前G列对应单元格

JUMU实名认证 发表于 2025-08-21 16:43 | 显示全部楼层 | 复制链接分享      上一主题  翻页  下一主题
Excel VBA 编程:从当前sheet中H列第2行单元格开始,在文件“C:\XX.XLSX”中D列依次搜索是否有相同的内容,如果找到相同单元格内容,那么,复制F列内容到当前F列对应单元格,复制G列内容到当前G列对应单元格。

  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:\00.XLSX"
  12.     Set wsCurrent = ThisWorkbook.ActiveSheet
  13.    
  14.     ' 打开目标工作簿,若已打开则直接设置
  15.     On Error Resume Next
  16.     Set wbSource = Workbooks("0带结构BOM.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
  24.     lastRowSource = wsSource.Cells(wsSource.Rows.Count, "D").End(xlUp).Row
  25.    
  26.     ' 建议为了效率,将目标表D列内容加载到字典中
  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, "D").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)
  41.         If dict.Exists(currentVal) Then
  42.             sourceRow = dict(currentVal)
  43.             wsCurrent.Cells(i, "F").Value = wsSource.Cells(sourceRow, "F").Value
  44.             wsCurrent.Cells(i, "G").Value = wsSource.Cells(sourceRow, "G").Value
  45.         End If
  46.     Next i
  47.    
  48.     ' 关闭目标工作簿(可选),如果不想保存改动
  49.     wbSource.Close SaveChanges:=False
  50.     MsgBox "完成数据复制!"
  51. End Sub
复制代码


  距米网  

找到您想要的设计

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

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

©2017-2025 苏ICP备18040927号-1