You are on page 1of 11

Copy a range from closed workbooks (ADO)

Ron de Bruin (last update 9-Jan-2008) Go back to the Excel tips page

Information
The basic examples in the workbook that you can download use ADO to copy data from a closed workbook or workbooks without opening the workbook or workbooks. This can be very fast to merge data from many workbooks but when you open workbooks with code you have much more control and more options. See the pages below if you want to open the files with code and merge the data Merge data from all workbooks in a folder(1) http://www.rondebruin.nl/copy3.htm Merge data from all workbooks in a folder(2) http://www.rondebruin.nl/fso.htm RDBMerge Add-in (very easy) http://www.rondebruin.nl/merge.htm

Important info about the ADO examples


1) The code in the workbook is working in Excel 2000-2007. 2) In a Database you cannot mix data types, a column must be all numbers or all text. If there are different data types in the column ADO will copy only the Data type that have the majority. 3) If you want to copy only one cell from each workbook then use A3:A3 and not A3 in the code.

How do I use ADO


Click here to Download a example workbook with 7 code examples and also a data file named test.xls. With this two workbooks you can test the code (copy both files in the same folder). Note: Read the info on the worksheet and also the commented lines in the macro's. All macros in the Ado Tester.xls file call a macro named GetData that do almost all the work. There are six arguments in this macro Public Sub GetData(SourceFile As Variant, SourceSheet As String, _ SourceRange As String, TargetRange As Range, Header As Boolean, UseHeaderRow As Boolean) If we look at the first test macro that copy "A1:C5" from "Sheet1" in the test.xls workbook we see:

GetData ThisWorkbook.Path & "\test.xls", "Sheet1", _ "A1:C5", Sheets("Sheet1").Range("A1"), True, True


1) SourceFile : Path/Name of the source file ThisWorkbook.Path & "\test.xls" 2) SourceSheet : Name of the sheet in the SourceFile "Sheet1" 3) SourceRange : Range in the SourceSheet "A1:C5" Note: You can also use a named range if you want like "MyRange". leave the SourceSheet argument empty "" if you want to copy from a workbook level name. 4) TargetRange: Destination Sheet/Range Sheets("Sheet1").Range("A1") 5) Header: Does the range have a header row? True

6) UseHeaderRow :Do you want to copy the header row ? True I hope that it is easy to use the code examples in the Ado Tester.xls file. Let me know if you have suggestions or problems with the code. Remember that I am a simple Excel user and no ADO expert.

More information
Ole P. Erlandsen's Web Site http://www.erlandsendata.no/english/index.php?t=envbadac John Walkenbach http://www.j-walk.com/ss/excel/tips/tip82.htm Create a summary worksheet from different workbooks (with formulas) http://www.rondebruin.nl/summary2.htm Copy a range from closed workbook (Local, Network and on the internet) http://www.rondebruin.nl/copy7.htm

Copy a range from closed workbook (Local, Network and on the internet)
Ron de Bruin (last update 1 May 2006) Go to the Excel tips page You can find three examples here to get a range out of a closed workbook. Note: All examples use the GetRange macro. 1: file on the internet (this file exist on my site) 2: file in network folder 3: File in local folder Other useful pages are : http://www.rondebruin.nl/ado.htm http://www.rondebruin.nl/summary2.htm http://www.j-walk.com/ss/excel/tips/tip82.htm Note: there are five arguments in the macro's 1: Path 2: File name 3: Source sheet name 4: Source range 5: Destination sheet/range Note: There is no error check on this moment for the path and file and sheet name. Sub File_On_Website() Application.ScreenUpdating = False On Error Resume Next

'Call the macro GetRange GetRange "http://www.rondebruin.nl/files", "test1.xls", "Sheet1", "A1:B100", _ Sheets("Sheet1").Range("A1") On Error GoTo 0 Application.ScreenUpdating = True End Sub Sub File_In_Network_Folder() Application.ScreenUpdating = False On Error Resume Next 'Call the macro GetRange GetRange "\\Jdb\shareddocs", "test2.xls", "Sheet1", "A1:B100", _ Sheets("Sheet1").Range("A1") On Error GoTo 0 Application.ScreenUpdating = True End Sub Sub File_In_Local_Folder() Application.ScreenUpdating = False On Error Resume Next 'Call the macro GetRange GetRange "C:\Data", "test3.xls", "Sheet1", "A1:B100", _ Sheets("Sheet1").Range("A1") On Error GoTo 0 Application.ScreenUpdating = True End Sub

Main macro
Sub GetRange(FilePath As String, FileName As String, SheetName As String, _ SourceRange As String, DestRange As Range) Dim Start 'Go to the destination range Application.Goto DestRange 'Resize the DestRange to the same size as the SourceRange Set DestRange = DestRange.Resize(Range(SourceRange).Rows.Count, _ Range(SourceRange).Columns.Count) 'Add formula links to the closed file With DestRange .FormulaArray = "='" & FilePath & "/[" & FileName & "]" & SheetName _ & "'!" & SourceRange 'Wait

Start = Timer Do While Timer < Start + 2 DoEvents Loop 'Make values from the formulas .Copy .PasteSpecial xlPasteValues .Cells(1).Select Application.CutCopyMode = False End With End Sub

Excel - can I copy "2" different Ranges from closed workbook (VBA)
Asked By DarnToot on 18-Jan-08 09:35 AM I am using Ron DeBruins code to accomplish my original task. (works great) http://www.rondebruin.nl/copy1.htm#workbook But recently more data is needed from a second sheet within the same workbook(s) that I am retreiving my data from. Is there a way to add code to this example to include a second range of data from the same workbook? Thank you in advance for the help....
Ads by Google

1. Budget Worksheet - Track & Manage All Your Finances in One Place with 100% Free Mint! - Mint.c

DarnToot replied on 18-Jan-08 09:39 AM opps wrong reference below.. the correct link is>>http://www.rondebruin.nl/ado.htm Ron de Bruin replied on 18-Jan-08 09:43 AM Hi DarnTootn Yes that is possible Post the two ranges then I will reply with a working example Do you want to copy them (the two ranges) below each other or next to each other. -Regards Ron de Bruin http://www.rondebruin.nl/tips.htm Ron de Bruin replied on 18-Jan-08 09:49 AM http://www.rondebruin.nl/ado.htm You can repeat this line with a different range and dest cell GetData ThisWorkbook.Path & "\test.xls", "Sheet1", _ Tell me in which example you want to use it in the example workbook if you can't make it work.

-Regards Ron de Bruin http://www.rondebruin.nl/tips.htm DarnToot replied on 18-Jan-08 09:54 AM I am referencing your Sub GetData_Example5() Dim SaveDriveDir As String, MyPath As String Dim FName As Variant, N As Long Dim rnum As Long, destrange As Range Dim sh As Worksheet 'Get the cell values and copy it in the destrange 'Change the Sheet name and range as you like GetData FName(N), "STATS", "A2:AD2", destrange, False, False GetData FName(N), "Billing Sheet", "J42:K43"<< this is the new DATA needed...... Ron de Bruin replied on 18-Jan-08 10:06 AM You can try this Because the first range is one row we use offset to go one row down to paste the new data GetData FName(N), "Billing Sheet", "J42:K43", destrange.Offset(1, 0), False, False -Regards Ron de Bruin http://www.rondebruin.nl/tips.htm DarnToot replied on 18-Jan-08 10:16 AM I need to copy the new data on the same line as the original data.. and actually I do not need All the info just the J42 cell...(i should just write it as J42:J42) anyway here is the code I have.. So I would need the Data from J42 on the Billing sheet to go to AE2 on the new worksheet that this code generates.. so what I want it to do is basically add one more Cell on the same line.... So I need the DATA from J42 to go to AE2 on the new worksheet along with the other DATA from the getdata I have below... Sub Dim Dim Dim Dim GetData_Example5() SaveDriveDir As String, MyPath As String FName As Variant, N As Long rnum As Long, destrange As Range sh As Worksheet 'or use "C:\Data"

SaveDriveDir = CurDir MyPath = Application.DefaultFilePath ChDrive MyPath

ChDir MyPath FName = Application.GetOpenFilename(filefilter:="Excel Files,*.xls", _ MultiSelect:=True) If IsArray(FName) Then ' Sort the Array FName = Array_Sort(FName) Application.ScreenUpdating = False 'Add worksheet to the Activeworkbook and use the Date/Time as name Set sh = ActiveWorkbook.Worksheets.Add sh.Name = Format(Now, "mm-dd-yy h-mm-ss") 'Loop through all files you select in the GetOpenFilename dialog For N = LBound(FName) To UBound(FName) 'Find the last row with data rnum = LastRow(sh) 'create the destination cell address Set destrange = sh.Cells(rnum + 1, "A") ' For testing Copy the workbook name in Column E sh.Cells(rnum + 1, "E").Value = FName(N) 'Get the cell values and copy it in the destrange 'Change the Sheet name and range as you like GetData FName(N), "STATS", "A2:AD2", destrange, False, False Next End If ChDrive SaveDriveDir ChDir SaveDriveDir Application.ScreenUpdating = True End Sub Ron de Bruin replied on 18-Jan-08 10:31 AM Try this then GetData FName(N), "STATS", "A2:AD2", destrange, False, False GetData FName(N), "Billing Sheet", "J42:J42", destrange.Offset(0, 32), False, False Change the 32 to the column if it is not the correct one Change this also -Regards Ron de Bruin http://www.rondebruin.nl/tips.htm DarnToot replied on 18-Jan-08 10:49 AM Thank you Ron your a life saver... That works with a little tweak... (0, 30) was the only change that I had to make... THANK YOU THANK YOU!!!!!!!!!!

Ron de Bruin replied on 18-Jan-08 11:03 AM You are welcome Thanks for the feedback -Regards Ron de Bruin http://www.rondebruin.nl/tips.htm

Copy various cells from closed workbook to an open workbook

Darlene Sippio asked May 6, 2009 | Replies (9)

I need a code that would copy from one workbook to another but it has to contain code that will copy from different parts of the closed workbook and various worksheets. For instance copy from B9:W" to the end but copy to column c-x of the open workbook. It also needs to copy across then down. I prefer that the closed workbooks don't open and if a new file is needed to added to the workbook, all the new information will copy to the end of the existing information already in the workbook. In the closed workbook there are three worksheets within the workbook that I want to extract data from in different cells. I want to be able to tell the closed workbook which cells to go to and get the data from and then put in an open workbook filling in across. In the closed workbook I want to pull from the Customer_Information worksheet cell B5, and then from the OperationsBid worksheet I want to pull from B9:W?, not knowing where W ends. But for each line pulled from the OperationsBid the B5 from the Customer_Information has to be repeated each time filled across and then down. Then for each line of the operationsbid worksheet, there is a matching line on the summary page which I only needs data from one column to match what is pulled from the operationsbid worksheet. I've atttached a worksheet that has the first tab as the layout and an example of the three worksheets out of each closed workbook the information I need to pull. These worksheets are exactly like the onese in all the closed files.
Join this group

Popular White Paper On This Topic

The Dos and Don'ts of ERP Implementations


9 Replies
0

Darlene Sippio replied Jan 1, 0001


To be more explanatory, the files are in one folder that contains several folders. What I need is for the code to read all the files even in sub-directories. 0

David Cross replied Jan 1, 0001


I do not know a way to change values of files without opening them. but the opening could be automated and temporary. I've created an Excel tool that takes data from a source table and posts or updates appropriate cells in a table on one or two destination worksheets- which could be in separate/different workbooks. The rows need unique identifiers to allow a match up between source and destination, but the columns can be in different order. the opening of the workbooks could be automated if you or the user supply the folder information. in short, this tools automates the process of copying data from one table and entering it in the correct cell in another table, when the columns may be labeled differently and in different order. You might be able to adapt this tool or some of the code to your purpose. I could send you the workbook if I can get your email address mineisdavidperiodcrossataecomperiodcom

Michael Meyers-Jouan
Darlene,

replied Jan 1, 0001

The following is a suggestion of how you can achieve what you're asking. I've made a couple of assumptions: 1. When you write "the B5 from the Customer_Information has to be repeated each time filled across and then down", you mean that you want the value from B5 put in Column B for each line copied. 2. When you write "there is a matching line on the summary page which I only needs data from one column to match what is pulled from the operationsbid worksheet" you are simply copying a value from a fixed column, from a row that corresponds to the row copied from the operationsbid worksheet (you're not doing a search or lookup in the summary sheet). In the code, you would execute CopyFromFiles once. It begins the process of scanning the tree of folders. Note that, because you didn't specify which column in the summary worksheet to copy, I have used a placeholder. .. Option Explicit Public Sub CopyFromFiles() ' ' Make the opening and closing of the workbooks invisible ' ..Application.ScreenUpdating = False ' ' Start the recursive directory walk ' ..Call CopyFromDirectory("C:\MyStartingFolder") ' ' Restore normal display ' ..Application.ScreenUpdating = True End Sub Public Sub CopyFromDirectory(aDirPath As String) ..Dim dirPath As String ..Dim filePath As String .. ' ' Start the process of looking at subsidiary directories ' ..dirPath = Dir(aDirPath, vbDirectory) ' ' Loop through the subsidiary directories (if any), ' calling myself recursively ' ..While dirPath <> "" ....Call CopyFromDirectory(dirPath) ....dirPath = Dir() ..Wend ' ' Start the process of looking at files in this directory ' ..filePath = Dir(aDirPath & "*.xls", vbNormal) ' ' Loop through all the files in this directory ' ..While filePath <> "" ....Call CopyFromAFile(filePath) ....filePath = Dir() ..Wend End Sub Public Sub CopyFromAFile(aFilePath As String) ..Dim sourceBook As Workbook

..Dim sourceSheet As Worksheet ..Dim targetSheet As Worksheet ..Dim sourceRow As Long ..Dim targetRow As Long ..Dim i As Long ..Dim j As Integer ..Dim iActual As Long ..Dim bValue As String .. ' ' Make it easier to refer to this workbook ' ..Set targetSheet = ActiveSheet ' ' We will start with the row FOLLOWING the last used row ' ..targetRow = targetSheet.UsedRange.Rows.Count + 1 ' ' Open the source file ' ..Set sourceBook = Application.Workbooks.Open(aFilePath) ' ' Get a copy of cell B5 ' ..bValue = sourceBook.Worksheets("Customer_Information").Rang e("B5").Value ' ' Point at the source worksheet for most of the data ' ..Set sourceSheet = sourceBook.Worksheets("OperationsBid") ' ' Determine how far down we have to copy ' ..sourceRow = sourceSheet.UsedRange.Rows.Count ' ' Perform the copy, row by row, ' and with in each row cell by cell ' ..For i = 9 To sourceRow ' ' Calculate the next row to fill: ' We started at targetRow, so we add i, but we subtract 9 because ' we don't want to skip the rows that we DIDN'T copy from the source ' ....iActual = targetRow + i - 9 ' ' Fill in column B ' ....targetSheet.Cells(iActual, 2) = bValue ....For j = 2 To 23 ' ' To copy B to C, we add one to the column number in the target ' ......targetSheet.Cells(iActual, j + 1) _ ........= sourceSheet.Cells(i, j) ....Next j ' ' For each row, add the summary value in a last column ' ....targetSheet.Cells(iActual, 25) sourceBook.Worksheets("summary").Cells(i, CInt("ColumnNumber")) ..Next i End Sub .. Michael S. Meyers-Jouan 0

Alun Davies

replied Jan 1, 0001

Isabella "I have a file which can either be txt or xml and gets created daily " Is there anyway you can have a fixed feed? With a fixed feed I think you stand half a chance.

White Papers and Webcasts


Popular

Related

Fuel for faster application delivery IOUG 2011 Survey: The Petabyte Challenge: 2011 IOUG ... MFT Center of Excellence White Paper IT Management - Enterprise WLAN Solutions Comparison Guide More White Papers
1

Isabella replied Jan 1, 0001


Michael , I am about to give your code a shot - is there a way to use different lines into different books eg below would copy the line 2 and the following would do line3- I have changed your code as per below - would this work? Call SaveLine("C:\My First Workbook", lineRead) ..Line Input #2, lineRead ..Call SaveLine("C:\My Second Workbook", lineRead) ..Line Input #3, lineRead ..Call SaveLine("C:\My Third Workbook", lineRead) 0

Michael Meyers-Jouan
Isabella, I think you may be trying too hard. ;<)

replied Jan 1, 0001

Let me explain what the "Line Input" statement does. The Line Input statement is one of a set of statements that work with files. These statements include the Open, Close, Line Input, and other statements. You can use these statements on a number of files at the same time; therefore, the statements require that you specify WHICH file to use, by using a "file number." The file number is something that you assign when you execute the Open statement. In my code, I used a file number of 1, because the code is only working with one file. That file number should then appear in ALL the statements that work with that file. When the Line Input statement is executed, it reads one line of text from the file (specified by the file number), and advances to the next line in the file. In other words, each Line Input statement gets the NEXT line of text. Therefore, if you execute six identical: ..

..Line Input #1, lineRead .. statements, you will read six DIFFERENT lines of text from the one input file. The first statement reads the first line, the second statement reads the second line, and so on. Therefore, you shouldn't need to change the code that I posted at all -except to replace the file names with the names and locations of the files you want to copy the data to. Michael S. Meyers-Jouan 0

Isabella replied Nov 22, 2009


Micheal, I have a similar situation, I was wanting to attach a jpg to show you but cant seem to do it here... I have a file which can either be txt or xml and gets created daily from avaya - i need the 6 lines in it, to each go to a different workbook and of course a different line every day for the different dates (eg: drop a line every day) Any ideas? 0

Michael Meyers-Jouan
Isabella,

replied Nov 23, 2009

Here's a very simple solution that assumes you simply want to copy the text of each line to the first column of each workbook: .. Option Explicit Public Sub ProcessAvayaFile() ..Dim lineRead As String .. ..Open "C:\Avaya.txt" For Input As #1 ..Line Input #1, lineRead ..Call SaveLine("C:\My First Workbook", lineRead) ..Line Input #1, lineRead ..Call SaveLine("C:\My Second Workbook", lineRead) ..Line Input #1, lineRead ..Call SaveLine("C:\My Third Workbook", lineRead) ..Line Input #1, lineRead ..Call SaveLine("C:\My Fourth Workbook", lineRead) ..Line Input #1, lineRead ..Call SaveLine("C:\My Fifth Workbook", lineRead) ..Line Input #1, lineRead ..Call SaveLine("C:\My Sixth Workbook", lineRead) End Sub Public Sub SaveLine(wbPath As String, inputLine As String) ..Dim wb As Workbook ..Dim ws As Worksheet ..Dim nextRow As Long ..wb = Application.Workbooks.Add(wbPath) ..ws = wb.Sheets(1) ..nextRow = ws.UsedRange.Rows.Count + ws.UsedRange.Row ..ws.Cells(nextRow, 1).Text = inputLine ..wb.Close SaveChanges:=True End Sub

You might also like