将CSV的特定单元格插入MS Access表vba

时间:2018-11-14 12:37:46

标签: vba csv ms-access

您好,我一直在尝试更新我们正在使用的csv的样式。目前,该样式对于导入器而言尚不可读,因此id必须编写一些vba才能使特定单元格进入列。

例如公司名称为A1

Yr1是F25,YR2是E25,YR3是D25,YR4是C25,YR5是B25 *这些都是日期

YR1的总销售额是F28,YR2 E28等,希望这足以说明一个例子。

因此,vba必须打开CSV并根据我想象的范围选择单元格,然后获取值,然后将其放入正确的列中。

希望这足以使我理解我想做的事情。 在CSV本身中,没有任何列标题。

我想像这样

Dim CombLoop As Integer
Dim CSVCn As Object
Dim rsCSV As Object
Dim strSql, CombFileName, GotoRange As String
Dim rs As DAO.Recordset

Set CSVCn = CreateObject("ADODB.Connection")
Set rsCVS = CreateObject("ADODB.Recordset")

'CSVCn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Q:\DATA\0091823.csv; Extended Properties = CSV;"

CSVCn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=Q:\UPDACOS\04369248.csv;" & _
"Extended Properties= Comma delimited;"

strSql = "SELECT * FROM [a1..f75];"
rsCSV.Open strSql, CSVCn, adOpenStatic

Set rs = CurrentDb.OpenRecordset("Select * From dbo_UpdatedRegtemp;")

If Not (rsCSV.EOF And rsCSV.BOF) Then
    FindRecordCount = rsCSV.RecordCount
    rsCSV.MoveFirst
    Do Until rsCSV.EOF = True
        Field1 = rsCSV![A1]
        Field3 = rsCSV![A2]
        Field2 = rsCSV![A3]
        rs.AddNew
        rs![Reg# Number] = Field1
        rs![Company Name] = Field2
        rs.Update
    rsCSV.MoveNext
    Loop
End If

cSVCn.Close
Set rsCSV = Nothing
Set CSVCn = Nothing
rs.Close

干杯

1 个答案:

答案 0 :(得分:0)

        Sub CSVData()
        Dim con As ADODB.Connection
        Dim rs As ADODB.Recordset

        Set con = New ADODB.Connection
        Set rs = New ADODB.Recordset

        Dim currentDataFilePath As String
        Dim currentDataFileName As String
        Dim nextRow As Integer
        Dim emptystr As String
         '"H:\projectfiles\csv\", "Book.csv"
        currentDataFilePath = ("H:\projectfiles\csv\")
        currentDataFileName = ("Book.csv")
         emptystr = "NULL"


        con.Provider = "Microsoft.Ace.OLEDB.12.0"
        con.ConnectionString = "Data Source=" & currentDataFilePath & ";" & "Extended Properties=""text;HDR=Yes;FMT=Delimited;"""
        'MsgBox currentDataFilePath

        con.Open

        rs.Open "SELECT * FROM [" & currentDataFileName & "] ", con
        rs.MoveFirst
        'nextRow = Worksheets("Sheet3").UsedRange.Rows.Count + 1
        'Worksheets("Sheet3").Cells(nextRow, 1).CopyFromRecordset rs

        'MsgBox rs.RecordCount
        With rs
        Do Until .EOF

        'check the field is not null before process

         If Not IsNull(rs(0)) Then
         custordernum = rs(0)
         End If

         If Not IsNull(rs(1)) Then
        ContactNAme = "" & Replace(rs(1), "'", " ")

        Else
        ContactNAme = emptystr
        End If

        If Not IsNull(rs(2)) Then
        colladd1 = "" & Replace(rs(2), "'", " ")
        Else
        colladd1 = emptystr
        End If
        MsgBox colladd1
        .MoveNext
        Loop
         End With


        rs.Close
        con.Close
        End Sub