【问题标题】:Sort/Manipulate Excel data from Access 2003 VBA从 Access 2003 VBA 排序/操作 Excel 数据
【发布时间】:2013-01-21 22:44:25
【问题描述】:

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

因此,在一个完美的场景中,代码将逐个单元格地遍历每一行,并获取用户、日期、单元格的数据和评论,并在现有的访问表中创建一条新记录。如果单元格是空的,那么它将被绕过。我有 4 张工作表,我知道如何制作代码循环,但我根本无法从 excel 中提取。

我也不想只导入数据,需要用cmets进行排序。

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

以下是我认为我得到的最接近的顺便说一句:

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

【问题讨论】:

  • 这是非常接近我正在寻找的,是的。但是,我没有让它逐行移动,而是试图让它逐个单元格地移动并挑选出带有数据的单元格。 .Rows.Count 会这样做吗?我正在阅读它,但只了解它的一部分...... 'If rng.Cells(i, 1) Like "Program*" Then' 是做什么的?我熟悉 If Then 语句,但我从未使用过 Like。谢谢
  • 没关系,我想通了。我只是需要更多地弄乱它。但是对于逐个单元格移动以检查是否为空或包含值,我是否应该使用一个整数,在到达每一行的末尾后重置为 1?
  • For i = 1 To rng.Rows.Count 适用于rng 范围内的每一行 i。您可以从行中获取单元格:For i = 1 To rng.Rows.Count For j = 1 To rng.Rows(i).Cells.Count Debug.Print rng(i, j) Next Next

标签: excel ms-access vba excel-2003


【解决方案1】:

感谢 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多