Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

MS Access VBA to copy Workbook Worksheet to another Workbook

Posted on 2013-05-15
9
Medium Priority
?
2,512 Views
Last Modified: 2013-05-21
Hello Experts,

Please provide assistance to include a MS Access table field that displays the Path and the File Name along with the Tab name as I am receiving a Run Time Error 1004 that displays " Output 1.xlsx could not be found".  I first tried the Spreadsheet Name then entered the Spreadsheet Tab inside the boded below statement – this is where the code stops. The Access table looks like:
ID      SpreadsheetName                                                                            SpreadsheetTab
1      X:\2013 reports\cfi consol nod 0313.xlsm                                       Output 1
2      X:\2013 reports\cfmi consol 0313.xlsm                                           Output 1
3      X:\Reports Close\CFMI Pre_Close_w_filters_RiskNEW.xlsm        Output 1 (100.100.T05)

and the VBA:
Private Sub WorksheetsCopy_Click()
Dim CopyFrom As Object
Dim CopyTo As Object
Dim CopyThis As Object
Dim xl As Object
Dim SpreadsheetName As String
Dim SpreadsheetTab As String
Dim ID As Field
Dim rs As Recordset
Dim sh As Worksheet
Dim oldPath As String, newPath As String
''Late binding
Set xl = CreateObject("Excel.Application")
xl.Visible = True
newPath = "H:\PDF"
Set rs = CurrentDb.OpenRecordset("TblReports")
Do While Not (rs.EOF)
Dim wkbSource As Excel.workbook
Dim wkbDest As Excel.workbook
Set wkbSource = Workbooks.Open(xl.Workbooks.Open(rs("SpreadsheetTab")))
Set wkbDest = Workbooks.Open("H:\PDF\MasterReport.xlsx")
    'Opens workbook
   Workbooks.Open "wkbSource"
   'Makes a copy of "Sheet1"
    ActiveWorkbook.Sheets("Sheet1").Copy _
       after:=ActiveWorkbook.Sheets("Sheet1")
       'Copies that copy to "wkbDest" workbook
        ActiveSheet.Move Before:=Workbooks("wkbDest").Sheets(1)
        ActiveSheet.Next.Select
       'Closes "wkbDest" workbook and saves the copied sheeet
       ActiveWorkbook.Close SaveChanges:=True
  rs.MoveNext
CopyFrom.Close False
Loop
rs.Close
End Sub

Thanks,
Bob
0
Comment
Question by:CFMI
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 39168045
Always, always, always qualify your references to external objects.



Private Sub WorksheetsCopy_Click()
Dim CopyFrom As Object
Dim CopyTo As Object
Dim CopyThis As Object
Dim xl As Object
Dim SpreadsheetName As String
Dim SpreadsheetTab As String
Dim ID As Field
Dim rs As Recordset
Dim sh As Worksheet
Dim oldPath As String, newPath As String
Dim wkbSource As Excel.workbook
Dim wkbDest As Excel.workbook
''Late binding
Set xl = CreateObject("Excel.Application")
xl.Visible = True
newPath = "H:\PDF"
Set rs = CurrentDb.OpenRecordset("TblReports")
Set wkbSource = xl.Workbooks.Open(xl.Workbooks.Open(rs("SpreadsheetTab")))
Do While Not (rs.EOF)
Set wkbDest = xl.Workbooks.Open("H:\PDF\MasterReport.xlsx")
   'Makes a copy of "Sheet1"
    wkbSource.Sheets("Sheet1").Copy _
       Before:=wkbDest.Sheets(1)
       'Closes "wkbDest" workbook and saves the copied sheeet
       wkbDest.Close SaveChanges:=True
  rs.MoveNext
Loop
wkbSource.Close False
rs.Close
Set wkbSource = Nothing
Set wkbDest = Nothing
xl.Quit
Set xl = Nothing
End Sub

Open in new window

0
 
LVL 1

Author Comment

by:CFMI
ID: 39168164
Using the above code received the same error message, "Run Time Error 1004 as Output 1.xlsx could not be found" - this points to Line #19; please help.
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 39168539
Private Sub WorksheetsCopy_Click()

    Dim xl As Object
    Dim rs As DAO.Recordset
    Dim wkbSource As Excel.workbook
    Dim wkbDest As Excel.workbook

    ''Late binding
    Set xl = CreateObject("Excel.Application")
    xl.Visible = True
    newPath = "H:\PDF"
    Set rs = CurrentDb.OpenRecordset("TblReports")
    Set wkbDest = xl.Workbooks.Open("H:\PDF\MasterReport.xlsx")

    Do While Not (rs.EOF)
        Set wkbSource = xl.Workbooks.Open(rs("SpreadsheetName"))
        'Makes a copy of "Sheet1"
        wkbSource.Worksheets(rs("SpreadsheetName")).Copy _
            Before:=wkbDest.Sheets(1)
        wkbSource.Close False
        rs.MoveNext
    Loop

    'Closes "wkbDest" workbook and saves the copied sheeet
    wkbDest.Close SaveChanges:=True

    rs.Close
    Set wkbSource = Nothing
    Set wkbDest = Nothing
    xl.Quit
    Set xl = Nothing

End Sub
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
LVL 1

Author Comment

by:CFMI
ID: 39168636
The above code receives a "Type Mismatched" error message and points to:
    wkbSource.Worksheets(rs("SpreadsheetName")).Copy _
        Before:=wkbDest.Sheets(1)

My guess is the Worsheet name is "Output 1" and it expects "Sheet 1".  The destination is to a Workbook with a worksheet named, "Sheet 1".
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 39168822
Sorry, that should be:

        wkbSource.Worksheets(rs("SpreadsheetTab")).Copy _
            Before:=wkbDest.Sheets(1)

Now, that places the copied worksheet before the first sheet overall.  To place it before "Sheet 1"...

        wkbSource.Worksheets(rs("SpreadsheetTab")).Copy _
            Before:=wkbDest.Sheets("Sheet 1")
0
 
LVL 1

Author Comment

by:CFMI
ID: 39168994
We now have anther error message stating, "Subscript out of range" using:
    wkbSource.Worksheets(rs("SpreadsheetTab")).Copy _
            Before:=wkbDest.Sheets("Sheet 1")
0
 
LVL 93

Accepted Solution

by:
Patrick Matthews earned 2000 total points
ID: 39169127
That tells me that either the worksheet we are trying to copy does not exist, and/or the worksheet we are referencing in the Before argument does not exist.

So:

1) Are you positive that the destination workbook has a sheet named "Sheet 1"?  Is it possible that it is named "Sheet1" (note the lack of a space)?

2) If the above checks out, if this happens again, type this in the Immediate window and hit Enter:

?"wb: " & wkbSource.Name & "; ws: " & rs("SpreadsheetTab")

Check to make sure that the indicated workbook does in fact have a worksheet with the indicated name.
0
 
LVL 1

Author Comment

by:CFMI
ID: 39169287
Both workbooks open, then I see the error message and the workbooks remain opened and are the correct workbooks but nothing is copied.  The error message states, "Subscript out of range" and debugging points to:
    wkbSource.Worksheets(rs("SpreadsheetTab")).Copy _
        Before:=wkbDest.Sheets("Sheet 1")")

Then I changed it to: Before:=wkbDest.Sheets("Sheet1")")  and I received Type mismatch.


Overall, I am reading in 53 specific Workbook, worksheets and coping them to a Master Workbook with 53 worksheets; perhaps I do not already need a spreadsheet with 53 worksheets especially since it doesn’t even seem to be copying?

Current code:
Private Sub TestCopy_Click()
Dim CopyFrom As Object
Dim CopyTo As Object
Dim CopyThis As Object
Dim xl As Object
Dim SpreadsheetName As String
Dim SpreadsheetTab As String
Dim ID As Field
Dim rs As Recordset
Dim sh As Worksheet
Dim oldPath As String, newPath As String
Dim wkbSource As Excel.Workbook
Dim wkbDest As Excel.Workbook
    ''Late binding
Set xl = CreateObject("Excel.Application")
xl.Visible = True
newPath = "H:\PDF"
Set rs = CurrentDb.OpenRecordset("TblReports")
'Set wkbSource = xl.Workbooks.Open(xl.Workbooks.Open(rs("SpreadsheetTab")))
Set wkbSource = xl.Workbooks.Open(rs("SpreadsheetName"))
Set wkbDest = xl.Workbooks.Open("H:\PDF\MasterReport.xlsx")
Do While Not (rs.EOF)
    Set wkbSource = xl.Workbooks.Open(rs("SpreadsheetName"))
    Set wkbDest = xl.Workbooks.Open("H:\PDF\MasterReport.xlsx")
        'Makes a copy of "Sheet1"
   wkbSource.Worksheets(rs("SpreadsheetTab")).Copy _
            Before:=wkbDest.Sheets("Sheet 1")    
       'Closes "wkbDest" workbook and saves the copied sheeet
    wkbSource.Close False
  rs.MoveNext
Loop
    'Closes "wkbDest" workbook and saves the copied sheet
wkbDest.Close SaveChanges:=True
wkbSource.Close False
rs.Close
Set wkbSource = Nothing
Set wkbDest = Nothing
xl.Quit
Set xl = Nothing

End Sub
MasterReport.xlsx
0
 
LVL 1

Author Closing Comment

by:CFMI
ID: 39184804
The code worked well but I was provided an incorrect worksheet title and this creates an out of sequence error so my learning, verify all input FIRST - Thanks!
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how you can use Custom Document Properties to store settings and other information in your workbook so that they will be available the next time you open the workbook.
Explore the ways to Unlock VBA Project Password Excel 2010 & 2013 documents. Go through the article and perform the steps carefully to remove VBA Excel .xls file.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question