VBA打开Excel文件并将工作表1数据粘贴到当前工作簿的“主”工作表中

时间:2015-10-26 18:31:32

标签: excel vba excel-vba

好的,我有一张工作簿(原始工作簿)和一张工作表。

我想打开一个现有的工作簿(数据工作簿)并复制“数据工作簿”的表1中的所有内容,然后将所有内容粘贴到Sheet" Main"原始工作簿'。

在此过程结束时,我想关闭数据工作簿'到目前为止,我有以下代码。

然而它给我一个错误信息

  

"运行时错误' 1004':无法将该宏公式粘贴到工作表上":

Sub ImportData()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range

Set wb1 = ActiveWorkbook
Set PasteStart = [Main!A1]

FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")

If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"

Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
    With Sheet.UsedRange
        .Copy PasteStart
        Set PasteStart = PasteStart.Offset(.Rows.Count)
    End With
Next Sheet
End If
wb2.Close

End Sub

1 个答案:

答案 0 :(得分:0)

您好请参考以下代码并根据您的需要进行更改。它可以满足您的需求。

Option Explicit
Sub import()
Dim filename As String
Dim curfilename As String

curfilename = ThisWorkbook.Name

filename = Application.GetOpenFilename
Application.ScreenUpdating = False

Dim x As Workbook
Set x = Workbooks.Open(filename)

With Sheets("1")
x.Sheets("1").Range("A1:Z10000").Copy   '/Provide the range
End With

Dim y As Workbook
Set y = Workbooks(curfilename)

With Sheets("Main")
y.Sheets("Main").Range("A1").PasteSpecial xlPasteFormats
Application.DisplayAlerts = False
End With

x.Close SaveChanges:=False
Range("A1").Select

End Sub