MS Access:导入规范无法通过VBA工作

时间:2013-05-17 18:27:00

标签: ms-access csv access-vba

我有一个csv文件的导入规范,当我通过GUI在文件上运行它时,工作得很好。但是,当我通过VBA运行它时,由于某种原因,它会忘记一列应该是一个Text列,而是使它成为一个Number列,从而导致大量错误。

我的代码如下。在所有内容都正常运行的意义上工作,但由于某种原因,CSV的导入规范无法正常运行。无意义的案例开关是占位符,因为我需要在第一次工作后添加更多类型的报告。

Sub ImportDE(Folder As Object)
Dim db As DAO.Database
Dim names As DAO.Recordset
Dim Files As Object, file As Object, SubFolders As Object, subfolder As Object
Dim ExString As Variant
Dim check As Boolean
Dim FileChange As String

Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh

Set names = CurrentDb.OpenRecordset("SELECT Old FROM DENames")

Set Files = Folder.Files
Set SubFolders = Folder.SubFolders

For Each subfolder In SubFolders
    ImportDE subfolder
Next

With names
    Do While Not .EOF
        ExString = .Fields(0)
        For Each file In Files
            If InStr(file.Type, "Worksheet") > 0 Then
                If InStr(file.Path, ExString & ".xls") > 0 Then
                    DoCmd.TransferSpreadsheet _
                        TransferType:=acImport, _
                        SpreadsheetType:=acSpreadsheetTypeExcel9, _
                        TableName:="tblImport_" & ExString, _
                        filename:=file.Path, _
                        HasFieldNames:=True, _
                        Range:="A:CT"
                    db.TableDefs.Refresh
                End If
            ElseIf InStr(file.Type, "Comma Separated") > 0 Then
                If InStr(file.Path, ExString & ".csv") > 0 Then
                    Select Case ExString
                    Case "Usage"
                        DoCmd.TransferText _
                            TransferType:=acImportDelim, _
                            SpecificationName:=UsageCSV, _
                            TableName:="tblImport_" & ExString, _
                            filename:=file.Path, _
                            HasFieldNames:=True
                        db.TableDefs.Refresh
                    End Select
                End If
            End If
        Next
        .MoveNext
    Loop
End With
db.Close:   Set db = Nothing
End Sub

我错过了一些明显的东西吗?为什么导入规范不能正常工作?

2 个答案:

答案 0 :(得分:2)

TransferText SpecificationName 参数应该是字符串表达式。由于代码没有声明名为UsageCSV的变量,我猜这是规范的文字名称。如果这是正确的,请将名称用双引号括起来。

DoCmd.TransferText _
    TransferType:=acImportDelim, _
    SpecificationName:="UsageCSV", _
    TableName:="tblImport_" & ExString, _
    filename:=file.Path, _
    HasFieldNames:=True

答案 1 :(得分:2)

在选项比较数据库之后的代码模块顶部 添加选项显式。 这将要求声明所有变量,并且永远不会再出现此问题