问题描述
目标是将所有excel文件导入一个文件夹中,以分隔各个工作表。我找到了这个脚本,却不知道在哪里问
Dim blnHasFieldNames as Boolean
Dim strWorksheet As String,strTable As String
Dim strPath As String,strPathFile As String
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = False
' Replace C:\Documents\ with the real path to the folder that
' contains the EXCEL files
strPath = "C:\Documents\"
' Replace worksheetname with the real name of the worksheet that is to be
' imported from each file
strWorksheet = "worksheetname"
' Import the data from each workbook file in the folder
strFile = Dir(strPath & "*.xls")
do while Len(strFile) > 0
strPathFile = strPath & strFile
strTable = "tbl_" & Left(strFile,InStrRev(strFile,".xls") - 1)
DoCmd.TransferSpreadsheet acImport,_
acSpreadsheetTypeExcel9,strTable,strPathFile,_
blnHasFieldNames,strWorksheet & "$"
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
' Kill strPathFile
strFile = Dir()
Loop
此处:http://www.accessmvp.com/KDSnell/EXCEL_Import.htm#ImpWktFilesSepTbls
我不知道如何使用代码(将其转换为宏吗?)还可以抓取第三行,例如将其作为标头?你知道我在哪里可以找到有关的信息吗?
谢谢
解决方法
您可以将数据从Excel导出到Access,然后从特定行开始。
Sub ADOFromExcelToAccess()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim cn As ADODB.Connection,rs As ADODB.Recordset,r As Long
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=C:\FolderName\DataBaseName.mdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "TableName",cn,adOpenKeyset,adLockOptimistic,adCmdTable
' all records in a table
r = 3 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("FieldName1") = Range("A" & r).Value
.Fields("FieldName2") = Range("B" & r).Value
.Fields("FieldNameN") = Range("C" & r).Value
' add more fields if necessary...
.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
或者,像现在一样导入所有内容,并在导入后在表上运行一个小的删除查询。
类似... Delete * from Table Where Field1 is ""
之类的东西。
下一个效果是完全一样的。