简体   繁体   English

从错误的单元格开始访问 VBA 导出到 Excel

[英]Access VBA Export to Excel starting in the wrong Cell

I've got a VBA script that exports data to a specific area in excel.我有一个 VBA 脚本,可以将数据导出到 excel 中的特定区域。 I've used the same snippet of code to accomplish this and about halfway through, the data stops going where it's supposed to.我使用了相同的代码片段来完成此操作,大约进行到一半时,数据停止了它应该去的地方。 If i tell it to start at BA4, it will starts at BA3.如果我告诉它从 BA4 开始,它将从 BA3 开始。 If I tell it to start at BD127, it will start at BD 3. I can have whatever field I want, provided it starts at row 3, and I have no idea why.如果我告诉它从 BD127 开始,它将从 BD 3 开始。我可以拥有我想要的任何字段,只要它从第 3 行开始,我不知道为什么。 Here is a section that works:这是一个有效的部分:

Set rec = db.OpenRecordset("SMG 6 AM-AR")

recCount = rec.Fields.Count
topLeft = "AM4"
botRight = "AR" & recCount
With objXL
    .Visible = False
    Set wb = .Workbooks.Open(mypath)
    On Error Resume Next
    Set ws = wb.Worksheets(2)
    Err.Clear
    On Error GoTo 0
    ws.Range(topLeft, botRight).CopyFromRecordset rec
  End With
  wb.Save

And here is a section that refuses to paste where I instruct it to:这是一个拒绝粘贴我指示它的部分:

Set rec = db.OpenRecordset("SMG 7 BL - BN 2")

recCount = rec.Fields.Count
topLeft = "BL4"
botRight = "BN" & recCount
With objXL
    .Visible = False
    Set wb = .Workbooks.Open(mypath)
    On Error Resume Next
    Set ws = wb.Worksheets(2)
    Err.Clear
    On Error GoTo 0
    ws.Range(topLeft, botRight).CopyFromRecordset rec
  End With
  wb.Save

Any suggestions are greatly appreciated.任何建议都非常感谢。

I would create a generic sub that takes parameters.我会创建一个带参数的通用子程序。 Then call this sub for each of your queries然后为您的每个查询调用此子程序

Something like this - not tested!!!像这样的东西 - 没有测试!!!

public sub insertData(objXL as Excel.Application, _ 
                      myPath as String, QueryName as string, _
                      byval startAddress as string)

dim rec as Recordset
Set rec = db.OpenRecordset(QueryName)

dim wb as Excel.Workbook, ws as Excel.worksheet
With objXL
    Set wb = .Workbooks.Open(mypath)
    Set ws = wb.Worksheets(2)
    ws.Range(startAddress).CopyFromRecordset rec
  End With
  wb.Save
End with 

End Sub

Your main sub might look like你的主子可能看起来像

Sub InsertAll

....

insertData objXL, "c:\wb1.xlsx", "SMG 6 AM-AR", "AM4"
insertData objXL, "c:\wb2.xlsx", "SMG 7 BL - BN 2", "BL4"

....

End sub

This way you can be sure that every step is really working the same way.通过这种方式,您可以确保每一步都以相同的方式工作。 And it is much easier to spot errors within the parameter section of each sub-call.而且在每个子调用的参数部分中发现错误要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM