从Excel连接到Access,然后从txt文件创建表

时间:2016-01-27 21:29:58

标签: vba

我正在为Excel工作簿编写VBA代码。我希望能够打开与Access数据库的连接,然后导入一个txt文件(管道分隔)并从该txt文件在数据库中创建一个新表。我到处搜索但无济于事。我只能找到VBA代码,它将从Access本身而不是Excel中实现。请帮忙!谢谢

2 个答案:

答案 0 :(得分:0)

Google"从excel VBA开放访问数据库"而且你会找到很多资源。这是一般的想法:

Dim db As Access.Application
Public Sub OpenDB()

Set db = New Access.Application
db.OpenCurrentDatabase "C:\My Documents\db2.mdb"
db.Application.Visible = True

End Sub

您还可以使用ODBC或ADODB等数据访问技术。如果您正在计划更广泛的功能,我会查看这些内容。祝你好运!

答案 1 :(得分:0)

我不得不这样做同样的问题。你在这里提出了一个小问题的大问题,但这是我解决最难的障碍。首先将文本文件的每一行解析为一个数组:

Function ParseLineEntry(LineEntry As String) As Variant
'Take a text file string and parse it into individual elements in an array.
    Dim NumFields As Integer, LastFieldStart As Integer
    Dim LineFieldArray() As Variant
    Dim i As Long, j As Long

    'Determine how many delimitations there are. My data always had the format
    'data1|data2|data3|...|dataN|, so there was always at least one field.
    NumFields = 0
    For I = 1 To Len(LineEntry)
        If Mid(LineEntry, i, 1) = "|" Then NumFields = NumFields + 1
    Next i
    ReDim LineFieldArray(1 To NumFields)

    'Parse out each element from the string and assign it into the appropriate array value
    LastFieldStart = 1
    For i = 1 to NumFields
        For j = LastFieldStart To Len(LineEntry)
            If Mid(LineEntry, j , 1) = "|" Then
                LineFieldArray(i) = Mid(LineEntry, LastFieldStart, j - LastFieldStart)
                LastFieldStart = j + 1
                Exit For
            End If
        Next j
    Next i

    ParseLineEntry = LineFieldArray
End Function

然后使用另一个例程添加连接(我正在使用ADODB)。我的参赛作品格式是TableName|Field1Value|Field2Value|...|FieldNValue|

Dim InsertDataCommand as String

'LineArray = array populated by ParseLineEntry
InsertDataCommand = "INSERT INTO " & LineArray(1) & " VALUES ("
For i = 2 To UBound(LineArray)
    If i = UBound(LineArray) Then
        InsertDataCommand = InsertDataCommand & "'" & LineArray(i) & "'" & ")"
    Else
        InsertDataCommand = InsertDataCommand & LineArray(i) & ", "
    End If
Next i

请记住,您必须在此处构建一些案例处理。例如,如果您有一个空值(例如Val1|Val2||Val4)并且它是一个字符串,则可以输入""它已经在ParseLineEntry数组中。但是,如果您将其输入数字列,它将失败,您必须在字符串中插入"Null"。此外,如果要添加带撇号的任何字符串,则必须将其更改为''。总而言之,我不得不逐字逐句地查找这些问题,但是这个概念得到了证明。

我使用相同的解析函数以编程方式构建了表,但是这种.csv格式:TableName|Field1Name|Field1Type|Field1Size|...|

同样,这是你正在解决的一个大问题,但我希望这个答案可以帮助你解决不太直接的问题。