试图将多个工作簿中的两个单元格复制到一个工作表中

时间:2018-09-13 16:31:21

标签: excel vba excel-vba

我正在尝试从文件夹中每个工作簿上的B2 & C2工作表中复制两个单元格Results,然后将单元格粘贴到从单元格A1, A2, A3 etc开始的主工作簿中

我找到了一个教程,几乎可以满足我的需求,我试图对其进行编辑。

我不确定如何将数据显示在母版中的同一工作表上,因为我认为这会在文件夹中为每个工作簿添加一个新表。

最后一行:ActiveWorkbook.Close Save = False

给我一​​个错误:Expected Function or Variable.,突出显示了Save

 'Copy cells B2 & C2 from the results worksheet
Worksheets("Results").Activate
ActiveSheet.Range(Cells(2, 2), Cells(3, 2)).Copy
ActiveWorkbook.Close Save = False

完整代码。

Sub LoopThroughDirectory()

Dim MyFile As String
Dim WorkbookCounter As Long
WorkbookCounter = 1
Dim Filepath As String

Filepath = "C:\Test\"

Application.ScreenUpdating = False
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0

Workbooks.Open (Filepath & MyFile)

'Copy cells B2 & C2 from the results worksheet
Worksheets("Results").Activate
ActiveSheet.Range(Cells(2, 2), Cells(3, 2)).Copy
ActiveWorkbook.Close Save = False

Application.DisplayAlerts = False

'Paste cells B2 & C2 to A1
Sheets(WorkbookCounter).Select
ActiveSheet.Paste Destination:=Worksheets(WorkbookCounter).Range("A1")
Application.CutCopyMode = False
WorkbookCounter = WorkbookCounter + 1
If WorkbookCounter > 1000 Then
Exit Sub
End If

MyFile = Dir
Loop
ActiveWorkbook.Save
Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

当您需要使用数字时,您正在使用字母作为列。你有:

ActiveSheet.Range(Cells(B, 2), Cells(C, 2)).Copy 

但是BC不是变量,Cells函数正在那里寻找列索引。将B和C分别替换为2和3。