欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > VBA实现遍历Excel文件将指定的单元格内容拷贝到当前工作簿

VBA实现遍历Excel文件将指定的单元格内容拷贝到当前工作簿

2025/6/18 16:50:37 来源:https://blog.csdn.net/colortztzztzt/article/details/144730791  浏览:    关键词:VBA实现遍历Excel文件将指定的单元格内容拷贝到当前工作簿

选择一个文件夹,遍历其中所有Excel文件,并将每个文件指定的单元格内容拷贝到当前工作簿的目标区域。

Sub 遍历文件拷贝指定区域内容()Dim folderPath As StringDim fileName As StringDim sourceColumns As StringDim targetRow As LongDim wbSource As WorkbookDim wsTarget As WorksheetDim wsSource As WorksheetDim lastRow As LongDim maxLastRow As LongDim sourceRange As RangeDim col As LongDim colStart As LongDim colEnd As Long' 初始化变量targetRow = 1 ' 起始行Set wsTarget = ThisWorkbook.Sheets(1) ' 当前工作簿的第一个工作表' 输入要拷贝的列范围sourceColumns = Application.InputBox("请输入要拷贝的列范围(例如 A:D):", "指定拷贝列范围", Type:=2)If sourceColumns = "" ThenMsgBox "未输入有效范围", vbExclamationExit SubEnd If' 选择文件夹With Application.FileDialog(msoFileDialogFolderPicker).Title = "选择包含Excel文件的文件夹"If .Show = -1 ThenfolderPath = .SelectedItems(1) & "\"ElseMsgBox "未选择文件夹", vbExclamationExit SubEnd IfEnd With' 遍历文件夹中的所有Excel文件fileName = Dir(folderPath & "*.xls*") ' 支持xls和xlsx格式Do While fileName <> ""' 打开每个Excel文件On Error Resume NextSet wbSource = Workbooks.Open(folderPath & fileName, ReadOnly:=True)If Not wbSource Is Nothing ThenOn Error GoTo 0Set wsSource = wbSource.Sheets(1) ' 默认取第一个工作表' 找到指定列范围的最后一行(所有列中最大的行号)colStart = Columns(Split(sourceColumns, ":")(0)).ColumncolEnd = Columns(Split(sourceColumns, ":")(1)).ColumnmaxLastRow = 0For col = colStart To colEndlastRow = wsSource.Cells(wsSource.Rows.Count, col).End(xlUp).RowIf lastRow > maxLastRow ThenmaxLastRow = lastRowEnd IfNext colIf maxLastRow >= 1 Then' 构建有效的范围Set sourceRange = wsSource.Range(wsSource.Cells(1, colStart), wsSource.Cells(maxLastRow, colEnd))' 拷贝指定范围内容到目标单元格sourceRange.CopywsTarget.Cells(targetRow, 1).PasteSpecial Paste:=xlPasteValuesApplication.CutCopyMode = False ' 取消选中状态' 更新目标行targetRow = targetRow + maxLastRowElseMsgBox "文件:" & fileName & " 中未找到内容", vbExclamationEnd IfwbSource.Close SaveChanges:=FalseElseMsgBox "无法打开文件: " & fileName, vbExclamationEnd IffileName = Dir ' 下一个文件LoopMsgBox "数据导入完成", vbInformation
End Sub

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com