Import identical excel files into access with multiple worksheets - excel

So, I'm trying to find ways to facilitate recombining data in excel sheets using access. What I am trying to do is take multiple excel files that are all identically formatted and concatenate them into a contiguous table. Right now I have a VBA function that will allow me to target one excel worksheet across a directory of excel files and combine them into one access table. My question is, how can I go about doing that same thing, but for EVERY worksheet in the directory in one shot, instead of running and modifying the code for every worksheet.
TL;DR You have 100 excel files, each with 7 worksheets in them. The formatting is identical, but the data is different. How do I take all 100 files and combine their worksheets into 7 respective MS Access tables?
****** ISSUE HAS BEEN SOLVED. WORKING CODE AS FOLLOWS *******
Module 1 named SingleModule:
Option Compare Database
Public Function importExcelSheets(Directory As String, TableName As String, WkShtName As String) As Long
On Error Resume Next
Dim strDir As String
Dim strFile As String
Dim I As Long
I = 0
If Left(Directory, 1) <> "\" Then
strDir = Directory & "\"
Else
strDir = Directory
End If
strFile = Dir(strDir & "*.XLSX")
While strFile <> ""
I = I + 1
strFile = strDir & strFile
Debug.Print "importing " & strFile
DoCmd.TransferSpreadsheet acImport, , TableName, strFile, True, WkShtName
strFile = Dir()
Wend
importExcelSheets = I
End Function
Module 2 named MultipleModule:
Public Function importMultipleExcelFiles(Directory As String) As Long
For x = 1 To 7
Dim TableName As String
Dim WkShtName As String
TableName = Choose(x, "Table1", "Table2", "Table3", "Table4")
WkShtName = Choose(x, "Table1!", "Table2!", "Table3!", "Table4!")
Call SingleModule.importExcelSheets(Directory, TableName, WkShtName)
Next x
End Function
Use the following command in the Immediate Window to execute (Make sure you change the filepath):
? importMultipleExcelFiles("C:\Excel File Directory")
SIDE NOTE:
You can target one worksheet using the following command on SingleModule in the Immediate Window:
? importExcelSheets("C:\FilePath", "TableName", "WkShtName!")

Sorry, I didn't see how your TableName was going into the procedure. Use the FOR-NEXT with the CHOOSE function, when you're calling the importExcelSheets function.
for x= 1 to 7
TableName = choose(x, "Table1", "Table2"...)
WkShtName = choose(x, "ContactDetails!", ...)
importExcelSheets Dir, TableName, WkshtName
next x

Related

How to check if a table exists in a sheet in a closed workbook without opening it

I have a macro that compiles rows within tables across multiple files. All files are essentially copies of the "master" file. Each file is used by a different person.
The rows to copy are on "Table_Data" in "Tracker" sheet, with these names being stored in constant variables.
The macro first checks if the pre-defined list of individual files exist in the same folder and are not open.
Once that check is passed, the files are opened one by one, with all data in the table read into an array.
That array is looped through to copy rows, that fit certain requirements, into a compiled array.
Once that is done, the array is emptied, file #1 is closed and file #2 is opened to repeat the above step.
Once all required rows have been copied into the compiled array, the array is pasted in the master file.
As part of error checking, I want to check if the pre-defined list of files have the correct sheetname and the correct table name inside that sheet, BEFORE opening the file. If one of the files is not valid, I don't want the compiler to start.
I found snippets of code, but I haven't been able to make any of them give me a True/False on whether or not the sheet and table exist on the file while the file is closed.
Checking If A Sheet Exists In An External Closed Workbook
Excel VBA - Get name of table based on cell address
I have this, however, the file has to be opened, which slows down the macro.
To save time, I call it before copying the rows from each file and if the file is not valid, do not compile and show message stating which files are not valid.
Option Explicit
Function IsFileValid(ByVal strFileName As String) As Boolean
Dim wb As Workbook
Application.ScreenUpdating = False
Set wb = Workbooks.Open(ThisWorkbook.Path & "\" & strFileName, True, True)
On Error Resume Next
If Worksheets(wrkshtTracker).ListObjects(tableTracker).Range(1, 2) = strEmailHeader Then
IsFileValid = True
End If
wb.Close False
Set wb = Nothing
On Error GoTo 0
Application.ScreenUpdating = True
End Function
I want this check before opening the files.
Let's say our excel file looks like this
Logic:
Copy the excel file to user temp directory and rename it to say "Test.Zip"
Unzip the Zip files
We will keep our attention to 2 different folders. \xl\worksheets and \xl\tables. This is where the xml files are created.
\xl\worksheets If a sheet exists then an xml will be created with that name as shown below.
\xl\tables If a table exists then an xml will be created as shown below. However in this case, it is not necessary that the name of the table will be the same as the file name. However the name of the table will be inside the xml file as shown below
and this is the content of the 2nd xml file.
So simply check if the xml file exists for the sheet and for the table, check the contents of the file.
Code:
Option Explicit
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Const MAX_PATH As Long = 260
Dim zipFilePath As Variant
Dim tmpDir As Variant
Dim filePath As String
Dim oApp As Object
Dim StrFile As String
Sub Sample()
filePath = "C:\Users\routs\Desktop\sid.xlsx"
tmpDir = TempPath & Format(Now, "ddmmyyhhmmss")
zipFilePath = tmpDir & "\Test.Zip"
MsgBox DoesSheetExist("Sheet1")
MsgBox DoesTableExist("Table13")
End Sub
'~~> Function to check if a sheet exists
Private Function DoesSheetExist(wsName As String) As Boolean
MkDir tmpDir
FileCopy filePath, zipFilePath
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(tmpDir & "\").CopyHere oApp.Namespace(zipFilePath).items
If Dir(tmpDir & "\xl\worksheets", vbDirectory) <> "" Then
StrFile = Dir(tmpDir & "\xl\worksheets\*.xml")
Do While Len(StrFile) > 0
If UCase(Left(StrFile, (InStrRev(StrFile, ".", -1, vbTextCompare) - 1))) = UCase(wsName) Then
DoesSheetExist = True
Exit Do
End If
StrFile = Dir
Loop
End If
If Len(Dir(tmpDir, vbDirectory)) <> 0 Then
CreateObject("Scripting.FileSystemObject").DeleteFolder tmpDir
End If
End Function
'~~> Function to check if a table exists
Private Function DoesTableExist(tblName As String) As Boolean
Dim MyData As String, strData() As String
Dim stringToSearch As String
stringToSearch = "name=" & Chr(34) & tblName & Chr(34)
MkDir tmpDir
FileCopy filePath, zipFilePath
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(tmpDir & "\").CopyHere oApp.Namespace(zipFilePath).items
If Dir(tmpDir & "\xl\tables", vbDirectory) <> "" Then
StrFile = Dir(tmpDir & "\xl\tables\*.xml")
Do While Len(StrFile) > 0
Open tmpDir & "\xl\tables\" & StrFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
If InStr(1, MyData, stringToSearch, vbTextCompare) Then
DoesTableExist = True
Exit Do
End If
StrFile = Dir
Loop
End If
If Len(Dir(tmpDir, vbDirectory)) <> 0 Then
CreateObject("Scripting.FileSystemObject").DeleteFolder tmpDir
End If
End Function
'~~> Function to get user temp directory
Private Function TempPath() As String
TempPath = String$(MAX_PATH, Chr$(0))
GetTempPath MAX_PATH, TempPath
TempPath = Replace(TempPath, Chr$(0), "")
End Function

Consolidation VBA of files in directory via ms-access

I have 33 linked tables all in same directory(sharepoint site). i would like some code to copy in all the tables in this directory and create a consolidated table of this data
all tables are same format and live in same folder.
i have tried Union and other ways but these have been restricted with the number of columns i could use.
The excel template has columns up to GG
You can try using Dir to loop through the directory, and use the DoCmd.TransferSpreadsheet to import the spreadsheets in that particular directory. Replace "YourTable" with your table name and "\yourdirectory\" with the location of the SP folder.
Sub ExcelImport()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("\\yourdirectory\")
While (file <> "")
If InStr(file, "xls") Or InStr(file, "xlsx") > 0 Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "YourTable", file, True
End If
file = Dir
Wend
End Sub
I'd do a similar thing to that mentioned by Ryan, but wouldn't import direct into the table I would want to query (mainly because there could be loads of housekeeping and/or data quality issues you may need to deal with first).
I'd first create a staging table with multiple alphanumeric fields (GG would take you to 189 fields; I'd call them F1-F189), PLUS a field to store the filename (and perhaps a couple of extra fields to handle the avoidance of duplicate records or to handle in-table updates - a datetimestamp and a process flag).
You can then have a loop that imports each file in turn into the staging table, and then within the loop execute a query (referring to a pre-written Access query is best as you will need to set up a Parameter to handle the filename; plus, you may want to tweak it over time) that will insert the records from the staging table into your proper destination table with the filename from your FOR-NEXT loop.
Within the loop, after you have imported each file you may then want to perform some housekeeping before moving onto the next file.
Below is something I've pretty much pasted in from what I use - it is messy, and it does use bits that are adapted from someone else's code, so I will credit that where I remember and apologies in advance for those I don't:
Sub import_ASSGMU()
' Macro loops through the specified directory (strPath)
' and imports Excel files to staging table in the Access Database
' (tbl_import_generic)
' before using an Access query to insert into the cleaned-up destination table
' (tbl_transformed_ASSGMU)
Dim strPath As String
strPath = "c:\data" ' YOU MUST SET YOUR OWN PATH HERE
If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
' this bit is if you want to move files out of the folder after they are processed
' Dim ImportSuccessPath As String
' ImportSuccessPath = "c:\data\Processed" 'hard-coded sub-folder name
' If Right(ImportSuccessPath, 1) <> "\" Then ImportSuccessPath = ImportSuccessPath & "\"
Dim strFile As String 'Filename
Dim strFileList() As Variant 'File Array
Dim intFile As Integer 'File Number
'Loop through the folder & build file list - file name prefix is HARDCODED
strFile = Dir(strPath & "ASSG_MU_*.xls*")
' this takes all the filenames and adds them to an array
While strFile <> ""
'add files to the list
intFile = intFile + 1
ReDim Preserve strFileList(1 To intFile)
strFileList(intFile) = strFile
strFile = Dir()
Wend
'see if any files were found
If intFile = 0 Then
'MsgBox "No files found"
Exit Sub
End If
' sorts the array so files are in filename order
' needs a procedure from here:
' http://www.access-programmers.co.uk/forums/showthread.php?t=194737
Call SortArray(strFileList())
' cycle through the list of files in the array & import to Access
For intFile = 1 To UBound(strFileList)
' empty staging table
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE FROM tbl_import_generic;"
DoCmd.SetWarnings True
' delete records from same filename previously imported
'DoCmd.SetWarnings False
' DoCmd.RunSQL "DELETE FROM tbl_transformed_ASSGMU WHERE import_file = """ & strFileList(intFile) & """;"
'DoCmd.SetWarnings True
' allows import of xls AND xlsx
If Right(strFileList(intFile), 1) = "s" Then
DoCmd.TransferSpreadsheet acImport, 8, "tbl_import_generic", strPath & strFileList(intFile), False, "A1:GG50000"
ElseIf Right(strFileList(intFile), 1) = "x" Then
DoCmd.TransferSpreadsheet acImport, 10, "tbl_import_generic", strPath & strFileList(intFile), False, "A1:GG50000"
End If
'DoCmd.Echo False, ""
DoCmd.SetWarnings False
Set db = CurrentDb
Dim qdf As DAO.QueryDef
' create an Access INSERT query with a name that matches the next code line that will take records from the tbl_import_generic and write them to the destination table. At this stage you can embed some hygeine factors or parse data in the Access query
Set qdf = db.QueryDefs("qry_transform_ASSGMU")
' create a Parameter called param_filename and use it to populate a
' destination field - this will then put the name of the imported
' file in your destination table
qdf!param_filename = strFileList(intFile)
qdf.Execute 'dbFailOnError ' useful when testing your query
DoCmd.SetWarnings True
' if you want to "move" files out of the folder when processed
' copy processed file to Processed folder & delete file from Import
' FileCopy strPath & strFileList(intFile), ImportSuccessPath & strFileList(intFile)
' Kill strPath & strFileList(intFile)
Next
MsgBox UBound(strFileList) & " file(s) were imported."
End Sub
Have a play around with it. Hope this is useful to you.

importing from an external souce where source filename changes

Forgive me if this is an easy problem, Im still learning..
I have an excel file, that takes data and performs analytics to compose graphs. right now method to update is manual copying and pasting from 2 other data sources. I can easily create a macro to import the first source as the data location/file name is always the same. The second source is trickier, as the file has some standardized naming convention, but a date is added, as it is refreshed once a week, every Monday or tuesday. is there a way to automate pulling the data from the external source (sharepoint library) and telling it to find the most current version? either by understanding the date convention added in the file name, or by another means of modified date or other criteria? the file is kept with previous archived copies. I do not own the report, sharepoint site, or library it is kept in, so I cant influence those factors :(. any help appreciated, and I can provide better details and explanation.
There are two basic approaches that I know of, either allow the user to choose the file through a dialog box, or use the "Dir" function to find the file with the most recent date.
First approach (code I use frequently):
Public Function ChooseOpenFile() As String
Dim strSlash As String
If InStr(1, ActiveWorkbook.Path, "/") > 0 Then
strSlash = "/"
Else
strSlash = "\"
End If
With Application.FileDialog(msoFileDialogOpen)
.Title = "Select the first file to open in series:"
.InitialFileName = Replace(ActiveWorkbook.Path, "http:", "", 1) & strSlash
Call .Filters.Clear
Call .Filters.Add("Excel Files Only", "*.xls, *.xlsx, *.xlsb")
'only allow the user to select one file
.AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = .Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
ChooseOpenFile = .SelectedItems(1)
End If
End With
End Function
As for the second approach, as long as you can already access the folder programmatically, you build a loop to cycle through the files, extract the date from each file, test for being more recent than previous versions and store the filename of the most recent version to pass out of the loop.
Function MostRecentFile() As String
Dim dateTest As Date
Dim dateRecent As Date
Dim strMyFile As String
Dim strMyFolder As String
Dim strCurrentFile As String
Dim strSlash As String
strMyFolder = ThisWorkbook.Path
If InStr(1, strMyFolder, "/") > 0 Then
strSlash = "/"
Else
strSlash = "\"
End If
strMyFile = Dir(Replace(strMyFolder, "http:", "") & strSlash & "*.xls*")
Do While strMyFile <> ""
'Modify this line (number of characters and extension to replace) as needed.
dateTest = CDate(Replace(Right(strMyFile, 15), ".xls*", ""))
If dateTest > dateRecent Then
dateRecent = dateTest
strCurrentFile = strMyFile
End If
Stop
Dir
Loop
MostRecentFile = strCurrentFile
End Function
You can browse to the file.
Sub GetOpenFile()
Dim fileStr As String
fileStr = Application.GetOpenFilename()
If fileStr = "False" Then Exit Sub
Workbooks.Open fileStr
End Sub
If you want some kind of automated solution, based on your system date, like the next Monday ot Tuesday, you can get the machine to figure it out, and pass the result to the appropriate string in the file path.
Sub NameAsNextMon()
Dim K As Integer
Dim dteMon As Date
Dim tempName As Variant
K = Weekday(Now)
dteMon = Now() + (9 - K)
tempName = Year(dteMon) & "-" & Month(dteMon) & "-" & Day(dteMon) & ".xls"
Do
fName = Application.GetSaveAsFilename(tempName)
Loop Until fName <> False
ActiveWorkbook.SaveAs Filename:=fName
End Sub

Vba to import a sub-portion of a hugh csv file into excel 2010

I have a csv file that has approx 600 fields and approx 100k of rows, i would like to import only select fields and only certian rows where a select set of fields match a certain set of criteria into an existing excel worksheet tab
I attempted to use ms query within excel but it stops at 255 columns, i can import the whole file in excel 2010 (250m) but it is a memory hog and by the time i remove the unneeded fields and rows it locks up my computer.
I would like to kick the import process off with an excel vba macro. I have all the front end code of file selection, etc.... But need some assistance in the text read query convert to excel area of vba
Any assitance would be greatly appreciated
Thanks
Tom
For that many records you would be better off importing the .csv into Microsoft Access, indexing some fields, writing a query that contains only what you want, and then exporting to Excel from the query.
If you really need an Excel-only solution, do the following:
Open up the VBA editor. Navigate to Tools -> References. Select the most recent ActiveX Data Objects Library. (ADO for short). On my XP machine running Excel 2003, it's version 2.8.
Create a module if you don't have one already. Or create one anyway to contain the code at the bottom of this post.
In any blank worksheet paste the following values starting at cell A1:
SELECT Field1, Field2
FROM C:\Path\To\file.csv
WHERE Field1 = 'foo'
ORDER BY Field2
(Formatting issues here. select from, etc should each be in their own row in col A for reference. The other stuff are the important bits and should go in column B.)
Amend the input fields as appropriate for your filename and query requirements, then run thegetCsv() subroutine. It will put the results in a QueryTable object starting at cell C6.
I personally hate QueryTables but the .CopyFromRecordset method I prefer to use with ADO doesn't give you field names. I left the code for that method in, commented out, so you can investigate that way. If you use it, you can get rid of the call to deleteQueryTables() because it's a really ugly hack, it deletes whole columns which you may not like, etc.
Happy coding.
Option Explicit
Function ExtractFileName(filespec) As String
' Returns a filename from a filespec
Dim x As Variant
x = Split(filespec, Application.PathSeparator)
ExtractFileName = x(UBound(x))
End Function
Function ExtractPathName(filespec) As String
' Returns the path from a filespec
Dim x As Variant
x = Split(filespec, Application.PathSeparator)
ReDim Preserve x(0 To UBound(x) - 1)
ExtractPathName = Join(x, Application.PathSeparator) & Application.PathSeparator
End Function
Sub getCsv()
Dim cnCsv As New ADODB.Connection
Dim rsCsv As New ADODB.Recordset
Dim strFileName As String
Dim strSelect As String
Dim strWhere As String
Dim strOrderBy As String
Dim strSql As String
Dim qtData As QueryTable
strSelect = ActiveSheet.Range("B1").Value
strFileName = ActiveSheet.Range("B2").Value
strWhere = ActiveSheet.Range("B3").Value
strOrderBy = ActiveSheet.Range("B4").Value
strSql = "SELECT " & strSelect
strSql = strSql & vbCrLf & "FROM " & ExtractFileName(strFileName)
If strWhere <> "" Then strSql = strSql & vbCrLf & "WHERE " & strWhere
If strOrderBy <> "" Then strSql = strSql & vbCrLf & "ORDER BY " & strOrderBy
With cnCsv
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & ExtractPathName(strFileName) & ";" & _
"Extended Properties=""text;HDR=yes;FMT=Delimited(,)"";Persist Security Info=False"
.Open
End With
rsCsv.Open strSql, cnCsv, adOpenForwardOnly, adLockReadOnly, adCmdText
'ActiveSheet.Range("C6").CopyFromRecordset rsCsv
Call deleteQueryTables
Set qtData = ActiveSheet.QueryTables.Add(rsCsv, ActiveSheet.Range("C6"))
qtData.Refresh
rsCsv.Close
Set rsCsv = Nothing
cnCsv.Close
Set cnCsv = Nothing
End Sub
Sub deleteQueryTables()
On Error Resume Next
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Dim qt As QueryTable
Dim qtName As String
Dim nName As Name
For Each qt In ActiveSheet.QueryTables
qtName = qt.Name
qt.Delete
For Each nName In Names
If InStr(1, nName.Name, qtName) > 0 Then
Range(nName.Name).EntireColumn.Delete
nName.Delete
End If
Next nName
Next qt
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
End Sub
You can parse your input file extracting the lines that conform to your criteria. The following code uses the split function on each line of the CSV file to separate the fields and then checks to see if it matches the required criteria. If all the criteria match then selected fields are saved in a new CSV file then you can just open the smaller file. You will need to set the microsoft scripting runtime reference in the VBA editor for this to work.
This method should use little memory as it processes 1 line at a time, I tested it on data of 600 fields and 100000 lines and it took about 45 seconds to process the file with no noticable increase in RAM usage in windows task manager. It is CPU intensive and the time taken would increase as the complexity data, conditions and the number of fields copied increases.
If you prefer to write directly to an existing sheet this can be easily acheived, but you would have to rememove any old data there first.
Sub Extract()
Dim fileHandleInput As Scripting.TextStream
Dim fileHandleExtract As Scripting.TextStream
Dim fsoObject As Scripting.FileSystemObject
Dim sPath As String
Dim sFilenameExtract As String
Dim sFilenameInput As String
Dim myVariant As Variant
Dim bParse As Boolean 'To check if the line should be written
sFilenameExtract = "Exctract1.CSV"
sFilenameInput = "Input.CSV"
Set fsoObject = New FileSystemObject
sPath = ThisWorkbook.Path & "\"
'Check if this works ie overwrites existing file
If fsoObject.FileExists(sPath & sFilenameExtract) Then
Set fileHandleExtract = fsoObject.OpenTextFile(sPath & sFilenameExtract, ForWriting)
Else
Set fileHandleExtract = fsoObject.CreateTextFile((sPath & sFilenameExtract), True)
End If
Set fileHandleInput = fsoObject.OpenTextFile(sPath & sFilenameInput, ForReading)
'extracting headers for selected fields in this case the 1st, 2nd and 124th fields
myVariant = Split(fileHandleInput.ReadLine, ",")
fileHandleExtract.WriteLine (myVariant(0) & "," & _
myVariant(1) & "," & _
myVariant(123))
'Parse each line (row) of the inputfile
Do While Not fileHandleInput.AtEndOfStream
myVariant = Split(fileHandleInput.ReadLine, ",")
'Set bParse initially to true
bParse = True
'Check if the first element is greater than 123
If Not myVariant(0) > 123 Then bParse = False
'Check if second element is one of allowed values
'Trim used to remove pesky leading or lagging values when checking
Select Case Trim(myVariant(1))
Case "Red", "Yellow", "Green", "Blue", "Black"
'Do nothing as value found
Case Else
bParse = False 'As wasn't a value in the condition
End Select
'If the conditions were met by the line then write specific fields to extract file
If bParse Then
fileHandleExtract.WriteLine (myVariant(0) & "," & _
myVariant(1) & "," & _
myVariant(123))
End If
Loop
'close files and cleanup
fileHandleExtract.Close
fileHandleInput.Close
Set fileHandleExtract = Nothing
Set fileHandleInput = Nothing
Set fsoObject = Nothing
End Sub

Import One Worksheet from Multiple Excel Files into Multiple Access tables

I have about 200 Excel files that I would like to import into a single Access database and have a table for each file. Each Excel file has multiple worksheets, but the one that I would like to import is consistently named.
I have found some code for this, see: http://www.accessmvp.com/KDSnell/EXCEL_Import.htm#ImpBrsFldFiles,
http://social.msdn.microsoft.com/Forums/en-US/dfea25ab-cd49-495c-8096-e3a7a1484f65/importing-multiple-excel-files-with-different-file-name-into-access-using-vba
Here is one of the pieces of code which I tried:
Option Compare Database
Sub ImportFromExcel()
End Sub
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String, strBrowseMsg As String
Dim blnHasFieldNames As Boolean
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = True
strBrowseMsg = "C:\Users\fratep\Desktop\Long-term EWM Study Data Files\"
strPath = BrowseFolder(strBrowseMsg)
If strPath = "" Then
MsgBox "No folder was selected.", vbOK, "No Selection"
Exit Sub
End If
' Replace tablename with the real name of the table into which
' the data are to be imported
strTable = "tablename"
strFile = Dir(strPath & "\*.xls")
Do While Len(strFile) > 0
strPathFile = strPath & "\" & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
' Kill strPathFile
strFile = Dir()
Loop
Sub ImportMultiExcels()
End Sub
from the 1st link above, but I can't seem to get them to do what I am looking for. Can anyone help me?
I am new to VBA, so am a little uncertain about editing the code.
It seems you're able to use the Import Wizard to successfully import a worksheet into Access. In that case, you should be able to use the DoCmd.TransferSpreadsheet Method to do the same thing from VBA code in your Access database.
The procedure below imports a single sheet named XYZ Priority as an Access table named Import1.
I used a constant for the sheet name because you said the target sheet has the same name in all the source workbook files.
I constructed the table name as "Import" plus i. When you extend this to multiple workbooks, you can increment i after each import. Or perhaps you have a different strategy for the table names; you didn't say.
I split the TransferSpreadsheet statement across several lines, and included the option names to (hopefully) make it easier to understand.
My worksheet includes column names, so I have HasFieldNames:=True
And my workbook was created with an older version of Excel. SpreadsheetType:=acSpreadsheetTypeExcel9 works with this; you may need a different value for SpreadsheetType
Public Sub Demo_TransferSpreadsheet()
Const cstrSheetName As String = "XYZ Priority"
Dim i As Long
Dim strFileName As String
Dim strTableName As String
' my workbook is located in the same folder as the Access db file
strFileName = CurrentProject.Path & Chr(92) & "temp.xls"
i = 1
strTableName = "Import" & CStr(i)
DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadsheetType:=acSpreadsheetTypeExcel9, _
Tablename:=strTableName, _
FileName:=strFileName, _
HasFieldNames:=True, _
range:=cstrSheetName & "$"
End Sub

Resources