【发布时间】:2022-01-19 17:33:53
【问题描述】:
嗨嗨, 免责声明:我没有编码经验 我有一个代码,它从桌面文件夹中的多个工作表中的单元格(B2:C2)中获取值并将其粘贴到主工作簿中。这很好用,但是,我不希望将复制的单元格连续粘贴到单元格 (F3:G3) 中——它们需要粘贴到特定的单元格中。这听起来很复杂,我敢肯定。首先,这是我修改的基本代码 (from this code) 以满足我的需要:
Sub MergeAllWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
' Set summarysheet to activeworkbook/activesheet where the macro runs
Set SummarySheet = ActiveWorkbook.ActiveSheet
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Users\Me\Desktop\Extracted Data\16.12.2021\"
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.csv*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
'loop through all Sheets in WorkBk
For Each sh In WorkBk.Worksheets
' Set the source range to be A9 through C9.
Set SourceRange = Sheets(sh.Name).Range("B2:C2")
' Set the destination range to start at column B and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("F" & SummarySheet.Range("F" & Rows.Count).End(xlUp).Row + 1)
Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
SourceRange.Columns.Count)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Value
Next sh
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
' Call AutoFit on the destination sheet so that all
' data is readable.
ActiveSheet.Columns.AutoFit
'Message Box when tasks are completed
MsgBox "Task Complete!"
End Sub
因此,这会运行并将源文件夹中每个工作簿中的值复制到主文件夹。我想这样做: 如果它从包含即“282579”和“Ch.4”的工作簿复制到与这些值对应的单元格。为了澄清,我在我的主工作簿中添加了一个Screenshot。 如果它从标题包含 282579 和 Ch.4 的源工作簿中复制一个值,它会将这两个值粘贴到位于 (F10:G10) 的 282579 的 Ch.4 单元格中,依此类推。 尝试使用 If 函数(例如,如果(工作簿的名称中有 this),但我不知道如何指定需要粘贴的单元格)
我希望我说得有道理并且这是可以理解的。
编辑:如果需要我使用的数据的副本,我可以提供它
【问题讨论】:
-
工作簿是否有多个工作表?
-
不,每个工作簿(包括母版和源版)只有一张。
-
好的,你在代码中'循环遍历 WorkBk
For Each sh In WorkBk.Worksheets中的所有工作表,这让我感到困惑。对于工作簿 282579 和 Ch.4,文件名是什么,它是282579Ch.4.xlsx,文件名中带有点? -
我刚刚从其他人那里复制了这个 here 我想我不需要它,但这不是我遇到的问题,因为它确实复制/粘贴到我的掌握。源文件名类似于:“VS SAAV_282579 ch 4 Data”(282579 和 ch 4 更改值)。这是一个 .csv 工作簿
标签: excel vba copy-paste