Home » excel » excel – When copying from one workbook to another, an "unwanted" workbook is created

excel – When copying from one workbook to another, an "unwanted" workbook is created

Posted by: admin May 14, 2020 Leave a comment

Questions:

So I have two excel workbooks – Workbook A is used as a userform and Workbook B as a database with all the data entries (B is a merged file). Whenever I open Workbook A, I would like to pull all the data from Workbook B automatically and copy it into Workbook A in a separate Worksheet. In doing so, I can implement some other functionalities like retrieval of previous entries.

So I used the following cod embedded in Workbook:

Public Sub Workbook_open()

Call get_AllUpdateEntries

End Sub


Sub get_AllUpdateEntries()

Dim oriWorkbook As Workbook
Dim destWorkbook As Workbook

Set oriWorkbook = Workbooks.Open("FilePath")
Set destWorkbook = ThisWorkbook

oriWorkbook.Worksheets("Sheet Name").Copy

destWorkbook.Worksheets("Sheet Name").Paste

x.Close SaveChanges:=False

End Sub

However, I cannot get this macro running. It doesn’t copy the Worksheet as I want, and additionally, another, unwanted Workbook is opened.

How to&Answers:

When you copy the worksheet to no location, it creates a new active workbook with a single worksheet (a copy of the original).

Provide an immediate destination for the copied worksheet.

Sub get_AllUpdateEntries()

    Dim oriWorkbook As Workbook
    Dim destWorkbook As Workbook

    Set oriWorkbook = Workbooks.Open("FilePath")
    Set destWorkbook = ThisWorkbook

    'remove the destination worksheet if it already exists
    on error resume next
    application.displayalerts = false
    destWorkbook.worksheets("All Update Entries").delete
    application.displayalerts = true
    on error goto 0

    'copy worksheet to the end of the worksheet queue in ThisWorkbook
    oriWorkbook.Worksheets("Sheet Name").Copy _
       After:=destWorkbook.Sheets(destWorkbook.Sheets.count)

    oriWorkbook.Close SaveChanges:=False

    'rename the transferred worksheet
    destWorkbook.Sheets(destWorkbook.Sheets.count).name = "All Update Entries"

End Sub