Search code examples
excelvbaexternal

Copying external Excel sheet to current workbook using VBA


I'm working on small project in which I need to add sheets to the currently open workbook from any external database of worksheets in another workbook. I made a form to import any sheet that is required in the currently open (active) workbook.

The sheets will be copied from remote (in any other folder but same computer) workbook. I am using following code but due to unknown reasons the sheets are NOT getting copied to my current workbook.

Dim wb As Workbook
Dim activeWB As Workbook
Dim FilePath As String
Dim oWS      As String
Set activeWB = Application.ActiveWorkbook

FilePath = "D:\General Required Docs\DATA.xlsm"

If optFirst.Value = True Then
   Application.ScreenUpdating = False
   Application.DisplayAlerts = False
   On Error Resume Next
   oWS = cboMaterial.Value
   Set wb = Application.Workbooks.Open(FilePath)
   wb.Worksheets(oWS).Copy      
   After:=Application.ActiveWorkbook.Sheets(ThisWorkbook.Sheets.count)
   activeWB.Activate
   wb.Close False

   Application.ScreenUpdating = True
   Application.DisplayAlerts = True

Solution

  • Change

    wb.Worksheets(oWS).Copy      
       After:=Application.ActiveWorkbook.Sheets(ThisWorkbook.Sheets.count)
    

    to

    wb.Worksheets(oWS).Copy      
       After:=activeWB.Sheets(activeWB.Sheets.count)
    

    assuming that oWS is the index of the worksheet you want to copy.