excel - VBA将文件夹中的所有文件导入Access
问题描述
目标是将所有 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 ""
的东西。
接下来的效果完全一样。
推荐阅读
- cassandra - 如何在 Cassandra 中获得 X% 百分位数
- java - 如何使用 Lombok 实例化具有许多对象作为字段的类?
- scripting - 在 PC 软件中执行任务的脚本
- ruby-on-rails - Rails 5.2 中的空帖子
- html - 未对齐的“轮廓”与奇数的 div
- html - 尝试获取带边框的图像以自动调整 flexbox div
- javascript - Javascript,用会话刷新创建的png文件
- web-config - 无效的 Web.config 配置数据
- python - 从返回数据创建饼图
- c# - 如果仅使用语句更改,则从 PR 中排除文件