To extract data from a file with VBA, you open the file with a workbook or file-system call, read the range or lines you need, and write the values into your destination sheet or array. The shortest working pattern is: set a reference to the source workbook with Workbooks.Open, copy or assign the used range, then close the source without saving. For text and CSV files, use Open ... For Input with Line Input, or query the file with ADO if you want to treat it like a table. The steps below cover the common cases and the traps that make extraction fail silently.
What You'll Need
- Excel with the Developer tab enabled (File > Options > Customize Ribbon > check Developer). Menu labels can differ slightly by version and region.
- The source file saved locally or on a reachable network share, with a known path. Avoid OneDrive placeholder files that are not downloaded.
- Macro security set to allow your code to run: Developer > Macro Security, or save the workbook as .xlsm.
- A destination workbook or sheet where the extracted values will land.
- For text files, knowledge of the delimiter (comma, tab, pipe) and whether the first row is a header.
Step-by-Step
- Decide the source type. If the file is .xlsx, .xls, .xlsb or .csv, Excel can open it directly. If it is .txt, .dat or a fixed-width export, read it line by line. If it is a database export, consider ADO. The method determines everything that follows.
- Declare your variables at the top of the module. Use
Dim src As Workbook,Dim ws As Worksheet,Dim lastRow As Long, and aDim path As Stringfor the file path. Explicit declarations prevent the silent Variant bugs that plague extraction code. - Build the path safely. Hard-code it only for a quick test. For anything reusable, use
Application.GetOpenFilenameso the user picks the file, or read the folder from a cell. Check the file exists withDir(path)before opening; if it returns an empty string, exit with a message. - Open the workbook without triggering events. Wrap the open in
Application.ScreenUpdating = FalseandApplication.DisplayAlerts = False, thenSet src = Workbooks.Open(path, ReadOnly:=True). Read-only prevents accidental edits and avoids lock conflicts when someone else has the file open. - Find the real extent of the data. Do not trust
UsedRangeblindly; it can include formatting far beyond the data. UselastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Rowon the key column, and the equivalent withEnd(xlToLeft)for the last column. If the sheet has blank rows in the key column, scan a column that is always populated. - Copy the values, not the formatting. The fastest reliable pattern is
destRange.Value = srcRange.Value, which transfers a 2D array in one call. AvoidCopyandPasteunless you need formats; they are slower and can carry conditional formatting and data validation you did not intend. - Handle text and CSV files. For a delimited text file, open it with
Open path For Input As #1, loop withLine Input #1, lineText, split on the delimiter withSplit(lineText, ","), and write each field to the next row. Close withClose #1in all cases, including error paths. For CSV files that Excel opens cleanly, the workbook method in steps 4 to 6 is simpler and preserves types better. - Write to the destination sheet. Clear the target range first, then assign the array. If you are appending, find the next empty row on the destination with the same
End(xlUp)technique and offset by one. - Close the source and restore settings. Use
src.Close SaveChanges:=False, then setApplication.ScreenUpdating = TrueandApplication.DisplayAlerts = True. Put the restore lines in an error handler so they run even if extraction fails. - Add a simple error handler. At the top of the routine use
On Error GoTo Cleanup. In the cleanup block, close any open file numbers, close the source workbook if it is still open, restore application settings, and show a message withErr.Description. This single habit prevents the most common "Excel is not responding" outcomes.
Common Mistakes
- Leaving the source workbook open. Every run leaves another hidden workbook in memory. Always close it, and close it in the error handler too.
- Using
ActiveWorkbookinstead of a named reference. If the user clicks another window mid-run,ActiveWorkbookpoints at the wrong file. Always hold aWorkbookvariable. - Assuming row 1 is the header and row 2 is data. Many exports have title rows, blank rows or merged cells at the top. Inspect the file first and set a start row explicitly.
- Trusting
UsedRange. A single formatted cell in row 1,000,000 makes the range enormous and the copy slow or out of memory. - Forgetting that CSV values arrive as text. Numbers with leading zeros, dates in local formats and currency symbols will not convert automatically. Convert explicitly with
CDbl,CLngorCDateafter checking the value is numeric. - Not releasing objects. Set workbook and range variables to
Nothingat the end of long-running routines to avoid memory growth in repeated runs.
Tips
- Read the whole range into a Variant array once, process it in memory, then write it back in one assignment. Looping cell by cell across thousands of rows is dramatically slower.
- Use
ThisWorkbookfor your own file and a separate variable for the source. Mixing them is a frequent cause of writing data into the wrong workbook. - Log the source path, row count and timestamp to a hidden sheet so you can tell which run produced which data.
- Test with a copy of the real file, not a hand-made sample. Real exports contain the blank rows, merged headers and text-formatted numbers that break naive code.
- If the source is a shared network file, open it read-only and handle the "file in use" prompt by setting
DisplayAlerts = Falseonly around the open call, then restoring it.
Troubleshooting
The macro runs but nothing appears. Check that you assigned to a specific sheet and range, not to an unqualified Range on whatever sheet happens to be active. Add a Debug.Print of the source row count and destination address.
Runtime error 1004 on open. The path is wrong, the file is locked, or the extension does not match the actual format. Verify with Dir and try opening manually once.
Only the first column arrives. The source range was one column wide, or the array was written to a single-column destination. Check the column count with srcRange.Columns.Count.
Dates and numbers come through as text. The source cells are formatted as text. Convert after reading, or use TextToColumns on the destination for a quick fix.
Excel freezes or runs out of memory. You are likely copying a huge used range or looping cell by cell. Restrict the range with End(xlUp) and switch to array assignment.
It works once, then fails on the second run. A previous run left the source open or left ScreenUpdating off. Add the cleanup block described in step 10.
Frequently Asked Questions
Can VBA read a file without opening it in Excel?
Yes for text files, using the Open ... For Input statement, and for structured data using ADO. Excel workbooks must be opened as a workbook object to read cell values reliably.
How do I extract data from a closed workbook?
Open it read-only with Workbooks.Open(path, ReadOnly:=True), read the range, then close it with SaveChanges:=False. There is no supported way to read cell values from a closed workbook without opening it.
Can I extract only certain columns or rows?
Yes. Build the source range explicitly, for example ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, 5)), or loop the array and copy only the column indexes you need.
Why is my extracted data one row off?
Most often the header row is included in the copy, or the destination starts one row lower than intended. Set the source start row and destination start row as named constants and check both.
Does this work on Mac?
Core workbook and text-file code works, but file paths use different separators and some Windows-only calls are unavailable. Use Application.PathSeparator rather than hard-coded backslashes.
How do I extract data from a PDF?
VBA cannot read PDF content natively. Convert the PDF to text or CSV with a dedicated tool first, then apply the text-file method above.