将列从一个工作簿复制到另一个工作簿

时间:2016-09-22 10:04:20

标签: vba excel-vba excel

我遇到了

  

运行时错误9

     

下标超出范围

这是我的代码:

Sub copydatatocreatereport()

Dim report As Workbook
Dim datafile As Variant

'report is the active workbook where I want data to paste
'datafile is workbook which has data I want to copy from

datafile = Application.GetOpenFilename
If datafile = "false" Then
    Exit Sub
End If

Workbooks.Open datafile

Workbooks("datafile").Worksheets("sheet1").Columns("a").Copy _
    Destination:=Workbooks("report").Worksheets("sheet1").Columns("a1")

End Sub

3 个答案:

答案 0 :(得分:1)

您需要将datafile设置为工作簿(到您尝试打开的工作簿)。

您需要将report设置为ActiveWorkbook(不推荐,最好使用代码所在的ThisWorkbook或特定的工作簿)。

您无法将整列粘贴到特定单元格。

Sub copydatatocreatereport()

Dim report          As Workbook
Dim datafile        As Workbook
Dim wbPath          As String

'report is the active workbook where i want data to paste
Set report = ActiveWorkbook  ' safer to have a name of Workbook or use ThisWorkbook (where this code lies)

wbPath = Application.GetOpenFilename
If wbPath = "False" Then
    MsgBox "No Workbook was selected", vbInformation
    Exit Sub
End If

' set datafile to Open workbook which I want to copy from
Set datafile = Workbooks.Open(wbPath)
datafile.Worksheets("Sheet1").Columns("A").Copy Destination:=report.Worksheets("Sheet1").Columns("A")

End Sub

答案 1 :(得分:0)

请注意,这是未经测试的,但应指向正确的方向

Sub copydatatocreatereport()
Dim Report As Workbook
Dim ReportPath As String

'Report is the workbook where I want to paste data. We want report to be the destination - we do not need to create an object for the currently open workbook
'ReportPath is the string used to open the Report workbook

'Allow the user to select a workbook string
ReportPath = Application.GetOpenFilename
'Exit if nothing is selected
If ReportPath = "" Then
    Exit Sub
End If

'Set Report object = to the selected workbook. This was missing previously
Set Report = Workbooks.Open(ReportPath)

'Paste column a from the currently open workbook to the desistination workbook
ThisWorkbook.Worksheets("sheet1").Columns("a").Copy _
    Destination:=Report.Worksheets("sheet1").Columns("a")

End Sub

答案 2 :(得分:0)

你必须:

  • 使用工作簿(数据文件)代替工作簿(“数据文件”)

  • 清除了数据文件中的非工作表名称字符

如下:

    Dim name As String

    datafile = Application.GetOpenFilename

    Workbooks.Open datafile

    name = Right(datafile, Len(datafile) - InStrRev(datafile, "\"))

     Workbooks(name).Worksheets("sheet1")....