我的VBA代码应该在MS Access中传输我的查询(没有标题)
在名为总计的现有Excel电子表格中单元格K17 。
当我运行模块时,在excel文件的属性下,上次修改时间确实更新到我运行模块时。但我在excel电子表格上看不到我的查询。
对我的代码的任何建议都将受到高度赞赏。非常感谢!
Sub TransToXL()
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Dim acRng As Variant
Dim xlRow As Integer
Dim qry As QueryDef
Dim rst As Recordset
Set xlApp = New Excel.Application
Set xlWB = xlApp.Workbooks.Open("C:\Users\MyName\Desktop\August 2017.xlsx")
Set xlWS = xlWB.Worksheets("Totals")
xlRow = (xlWS.Columns("K").End(xlDown).Row)
Set qry = CurrentDb.QueryDefs("DollarsSold")
Set rst = qry.OpenRecordset
Dim c As Integer
c = 11
xlRow = xlRow + 16
Do Until rst.EOF
For Each acRng In rst.Fields
xlWS.Cells(xlRow, c).Formula = acRng
c = c + 1
Next acRng
xlRow = xlRow + 1
c = 1
rst.MoveNext
If xlRow > 25 Then GoTo rq_Exit
Loop
rq_Exit:
rst.Close
Set rst = Nothing
Set xlWS = Nothing
xlWB.Close acSaveYes
Set xlWB = Nothing
xlApp.Quit
Set xlApp = Nothing
Exit Sub
End Sub
变量c是存储列号的变量,其中c = 1表示列A,11表示K.在此代码中,我对我设置xlRow+16
的方式感到困惑。 xlRow+16
,而c = 11并未指出K17。对此有何建议?谢谢!
答案 0 :(得分:0)
你有没有理由使用Do Until循环?如果记录集只有1行数据(总计),看起来你可以删除循环,只需使用类似的东西:
xlWS.Range("K17").Value = rst.Fields(0)
这将出现在“Set rst ..”行之后。