将txt / xlsx文件导入到宏访问的最快方法

问题描述 投票:-2回答:2

我想导入所有文件(文件夹中的txt或xlsx)我已经创建了宏来执行此操作。 (所有列都必须为char)

要导入txt文件,我生成schema.ini文件。要导入excel文件,我使用的是sql,但速度很慢,所以我选择了另一种方式。

两个宏创建表,然后将记录放入其中。

得分:Txt文件:18个文件,每个数据库有4列记录。 18个txt文件有249584,就像969 688个单元格。时间:20秒。

Excel文件:1个文件,8列,14000条记录,就像110880个单元格(单元格不为空) 时间:75秒。

P.S Everyfile有另一种结构(列数等)。数据库中的每个列都必须为Varchar(255)

顺便说一句:你知道在Access中将所有数据库导出到txt有什么好的解决方案吗?是否可以检查txt文件的代码页?(通过使用VBA或Emeditor。)

excel vba excel-vba ms-access
2个回答
1
投票

https://msdn.microsoft.com/en-us/library/office/ff835958.aspx

DoCmd.TransferText非常漂亮。您可能需要设置导入规范。

DoCmd.TransferText acImportDelim, "spec name", "table name", "filename"

使用excel文件,你有DoCmd.TransferSpreadsheet,它有自己的argumments,但你不能使用它的规范。您还可以编写代码来将excel文件读入文本分隔文件并在那里导入表单(我在reg上执行此操作)。

这是一种未经测试的方法来创建要使用的pipedelimited文本文件。这是未经测试的,我不愿意为你免费做任何其他事情。如果你不能在这里找出它,那就太糟糕了。你可以谷歌帮助填补空白的事情:后期绑定,写入文本文件,Dir函数,Excel范围到数组。

快乐编码:)

dim NewTextFile as String
dim oXL as Object
dim sep as string
dim path as string
dim fileName as string
Dim bringOver as variant
dim sheet as object
dim wholeline as string

sep "|"
path = "path to excel file"
fileName = "name of excelfile.xlsx"

NewTextFile = "path you want file saved to" & "\name.txt"
Set oXL = WorkBooks.Open(path & fileName)
With oXL
    Open NewTextFile For Output As #2
    For Each sheet in oXL.Sheets
        bringOver = sheet.UsedRange
        for i = LBound(bringOver,1) to UBound(bringOver,1)
            for j = LBound(bringOver,2) to UBound(bringOVer,2)
                wholeline = wholeline & bringOver(i,j) & sep
            next j
            Write #2, wholeline
            wholelline = vbNullString
        Next i
    Next sheet
End With

0
投票

您可以遍历所有文件,并导入每个文件,如下所示。

Private Sub Command1_Click()

 Dim strPathFile As String
 Dim strFile As String
 Dim strPath As String
 Dim strTable As String
 Dim blnHasFieldNames As Boolean

 ' Change this next line to True if the first row in CSV worksheet
 ' has field names
 blnHasFieldNames = True

 ' Replace C:\Documents\ with the real path to the folder that
 ' contains the CSV files
 strPath = "C:\your_path_here\"

 ' Replace tablename with the real name of the table into which
 ' the data are to be imported

 strFile = Dir(strPath & "*.csv")


 Do While Len(strFile) > 0
       strTable = Left(strFile, Len(strFile) - 4)
       strPathFile = strPath & strFile

       ' Link CSV Files
       DoCmd.TransferText acImportDelim, , strTable, strPathFile, blnHasFieldNames

       ' Import Excel Files
       ' DoCmd.TransferSpreadsheet , , strTable, strPathFile, blnHasFieldNames


 ' Uncomment out the next code step if you want to delete the
 ' file after it's been imported
 '       Kill strPathFile

       strFile = Dir()

 Loop

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.