Excel VBA粘贴错误“...的大小不一样......”

时间:2017-09-18 07:11:05

标签: excel vba excel-vba

注意:我是VBA和一般代码的新手

我尝试制作一个宏来整理多个工作簿中的数据并将其导入主工作簿('ZMaster')。

以下代码成功地从多个工作簿(来自文件C:\ AutoMelinh)中的单元格C5复制数据,并将它们粘贴到我的“ZMaster”工作簿的列中。

问题是我收到错误'您粘贴的数据与您选择的数据大小不同。你想要粘贴吗?'每次粘贴后都会出现这种情况,所以每次都要点击“确定”。复制的单元格格式将合并(在C5和D5之间)。我认为这是问题,但我不知道如何在VBA代码中缓解这个问题:

Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
    If MyFile = "ZMaster.xlsm" Then
    Exit Sub
    End If

    Workbooks.Open (Filepath & MyFile)
    Range("C5").Copy
    ActiveWorkbook.Close

    erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))
    MyFile = Dir

Loop
End Sub

编辑:我能够通过

解决问题
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\AutoMelinh\"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
    If MyFile = "ZMaster.xlsm" Then
    Exit Sub
    End If

    Application.DisplayAlerts = False

    Workbooks.Open (Filepath & MyFile)
    Range("C5").Copy
    ActiveWorkbook.Close

    erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 4))
    MyFile = Dir

    Application.DisplayAlerts = True

Loop
End Sub

1 个答案:

答案 0 :(得分:1)

您收到警告是因为您将一个单元格粘贴到4个单元格中

这应该不使用复制/粘贴

Sub LoopThroughDirectory()

    Dim Filepath As String
    Filepath = "C:\AutoMelinh\"

    Dim MyFile As String
    MyFile = Dir(Filepath)

    Dim erow As Range
    Dim wb As Workbook

    Do While Len(MyFile) > 0
        If MyFile = "ZMaster.xlsm" Then Exit Sub

        Set wb = Workbooks.Open(Filepath & MyFile)

        erow = Workbooks("ZMaster.xlsm").Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

        erow.Value = wb.Sheets(1).Range("C5").Value

        if isempty(erow) then erow.value = "----------"

        wb.Close
        MyFile = Dir

    Loop

End Sub