如何导入工作表列以激活工作簿

时间:2015-04-16 11:06:06

标签: excel vba excel-vba copy-paste

我想从用户选择的工作簿中导入特定列到activate-workbook。

复制并粘贴列时,无法将其粘贴到目标工作表中。我做错了什么?

这是我的代码:

Sub Import_sheet()

Dim fDialog As Office.FileDialog
Dim varFile As Variant
Dim wb As Workbook
Dim activeWB As Workbook
Set activeWB = Application.ActiveWorkbook

Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
   With fDialog
      .AllowMultiSelect = True
      .Title = "Select Files to prepare"
      .Filters.Add "All Files", "*.*"

      If .Show = True Then

        For Each varFile In .SelectedItems
            MsgBox varFile
            Application.ScreenUpdating = False
            Application.DisplayAlerts = False

            Set wb = Application.Workbooks.Open(varFile)
            'wb.Worksheets(1).Copy _
            After:=activeWB.Sheets(activeWB.Sheets.Count)

            wb.Sheets(1).Columns("C").Select
            Selection.Copy

            activeWB.Sheets("template").Columns("B").Select
            Selection.Paste 

            wb.Close False

            Application.ScreenUpdating = True
            Application.DisplayAlerts = True
        Next

      Else
         MsgBox "You clicked Cancel in the file dialog box."
      End If
   End With

End Sub

1 个答案:

答案 0 :(得分:0)

您需要在复制或粘贴之前激活工作簿,这样它才不会超出范围。

    wb.activate
    wb.Sheets(1).select
    wb.Sheets(1).Columns("C").Copy


    activeWB.activate
    activeWB.Sheets("template").select
    activeWB.Sheets("template").Cells("B1").Paste