从Access 2003 VBA排序/操作Excel数据

时间:2013-01-21 22:44:25

标签: vba excel-vba access-vba excel-2003 excel

我正在尝试在Access 2003中运行一个带有excel文件的模块,如果单元格中有信息,则复制A1,B1等中的字段标题和单元格,因为它遍历每一行。单元格中还有一些注释需要复制数据。

因此,在一个完美的场景中,代码将逐个单元地遍历每一行,并获取用户,日期,单元格的数据和注释,并在现有的访问表中创建新记录。如果单元格为空,则将绕过它。我有4张表,我知道如何进行代码循环,我根本无法从excel中获取。

我不想只是导入数据,需要按照评论进行排序。

任何建议都将不胜感激。谢谢!

下面是我认为最接近btw:

Sub copy3()

Dim rs2 As New ADODB.Recordset
Dim cnn2 As New ADODB.Connection
Dim cmd2 As New ADODB.Command

With cnn2
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=C:\FilePath.xls;" & "Extended Properties=Excel 8.0;"
.Open
End With

Set cmd2.ActiveConnection = cnn2
cmd2.CommandType = adCmdText
cmd2.CommandText = "SELECT * FROM [Jan-Mar$] Where [Name] IS NOT NULL"
rs2.Open cmd2

While Not rs2.EOF
...Not sure what to write here but I got a msgbox to appear...
rs2.MoveNext
Wend

1 个答案:

答案 0 :(得分:2)

感谢Remou的建议和帮助。这最终对我有用:

Set rs = db.OpenRecordset("TestTable")
xl.Visible = False

Set ws = xl.Workbooks.Open("C:\file.xls").Sheets("Jan-Mar")
Set rng = ws.UsedRange

'Row 1 is all dates so start at Row 2
For i = 2 To rng.Rows.Count
    'Column A contains names so start at Column B
    For j = 2 To rng.Rows(i).Cells.Count
        If rng.Cells(i, j) = "" Or rng.Cells(1, j) = "Total" Then

    Else
        On Error Resume Next
        rs.AddNew
        rs!EmployeeName = rng.Cells(i, 1)
        rs!Date = rng.Cells(1, j)
        rs!PointValue = rng.Cells(i, j)
        str = rng.Cells(i, j).Comment.Text
        str = Right(str, Len(str) - 14)
        'MsgBox str
        rs!Comments = str
        rs.Update
    End If
Next
Next
Set rs = Nothing
Set rng = Nothing
ws.Parent.Close
xl.Quit