【问题标题】:Using For loop for selecting specific Fields in Access and pasting them to excel使用 For 循环选择 Access 中的特定字段并将它们粘贴到 Excel
【发布时间】:2019-01-25 13:11:05
【问题描述】:

我制作了一个特定的访问表单,其中包含许多具有相同名称的字段,只是末尾的数字发生了变化。我有名为“Code1”、“Code2”、“Code3”等的字段。 我想将表单视图中的字段粘贴到 Excel 单元格。大约有150个字段,我不想一一添加。

我制作了一个打开 Excel 模板的按钮,并制作了一个 For 循环,但我被卡住了。思路是这样的:

Set MyXL = CreateObject("Excel.Application")

        With MyXL

        .Application.Visible = True
        .Workbooks.Open "F:\0. Main\01.Templates\Order.xltx"


        Dim broj As Variant
        broj = UCase(ID)

        Dim Kod As Variant
        Dim Tip As Variant
        Dim Kolic As Variant

        For i = 1 To 30

   -------> Kod = Code(i).Value
            .Worksheets("Sheet1").Cells(11 + i, 2).Value = Kod

   -------> Tip = Type(i).Value
            .Worksheets("Sheet1").Cells(11 + i, 3).Value = Tip

   -------> Tip = Qty(i).Value
            .Worksheets("Sheet1").Cells(11 + i, 3).Value = Kolic

        Next i

我不知道如何在 For 循环中包含 FieldName + (number)

【问题讨论】:

标签: excel vba ms-access


【解决方案1】:

请检查是否可以将整个记录集直接粘贴到 Excel 的范围内(将根据需要从 L2 开始覆盖):

.Worksheets("Sheet1").Cells(12, 2).CopyFromRecordset

如果可行,您可能需要在粘贴之前清除范围:

.Worksheets("Sheet1").Range("L2:N100000").ClearContent

如果这没有帮助,您可能需要在 Access e 中循环访问记录集。 G。像这样:

Set rs = CurrentDb.OpenRecordset("WhatEver", dbOpenDynaset)
If Not (rs.BOF And rs.EOF) Then
    rs.MoveFirst
    i = 1
    Do
        ... = rs.Fields("Code" & i).Value
        ...
        rs.MoveNext
        i = i + 1
    Loop Until i > 30 ' or Until rs.EOF
End If

【讨论】:

  • 我使用了旧的 For 循环,但添加了 Set rs = CurrentDb.OpenRecordset("WhatEver", dbOpenDynaset) 和 rs.Fields("Code" & i).Value 现在它可以工作了 :) 谢谢
【解决方案2】:
Option Compare Database
Sub Export()
Dim tableName As String

    tableName = InputBox("What is the name of the table you want to export?")
    Dim outputFileName As String
    outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, tableName, outputFileName, True

    Set myXl = CreateObject("Excel.Application")
    myXl.Visible = True
    myXl.workbooks.Open outputFileName

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2021-12-21
    • 2014-02-21
    • 2011-07-29
    相关资源
    最近更新 更多