我需要提供一个更新的VBA脚本,该脚本会将Access 2010请求的结果传输到当前内容之后的现有Excel文件中。
这是上一个使用Access 97的脚本。
DoCmd.TransferSpreadsheet acExport, , "Liste_factures_numero", "C:\Users\me\Desktop\copiedetravailvlvaccdb\reglements.xlsx", True
我尝试在Sendkeys指令周围添加Sleep命令,但它没有用。结果未被选中,因此不会被复制或粘贴。
作为最后的手段,我尝试使用DoCmd.TransferSpreadsheet创建一个新脚本,但我无法想象如何在现有内容之后添加新内容。
Private Sub CommandButton1_Click()
Dim wbInv As Workbook, wsInv As Worksheet
Dim wbSrc As Workbook, wsSrc As Worksheet
Dim lastrow As Long, r As Long
Dim path As String
Set wbSrc = ThisWorkbook
Set wsSrc = wbSrc.Sheets("1")
Set wbInv = Workbooks.Open("BasicInvoice.xlsx")
Set wsInv = wbInv.Sheets("BasicInvoice")
path = "C:\invoices\"
lastrow = wsSrc.Range("A" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
For r = 2 To lastrow
With wsInv
.Range("E9").Value = wsSrc.Cells(r, 1).Value
.Range("E10").Value = wsSrc.Cells(r, 2).Value
.Range("B9").Value = wsSrc.Cells(r, 3).Value
.Range("B16").Value = wsSrc.Cells(r, 4).Value
.Range("E16").Value = wsSrc.Cells(r, 6).Value
End With
With wbInv
.SaveCopyAs Filename:=path & wsInv.Range("E10").Value & ".xlsx"
.PrintOut copies:=1
End With
Next r
wbInv.Close SaveChanges = False
Application.ScreenUpdating = True
End Sub
然而正如预期的那样,它会覆盖内容。 这是我第一次使用VBA。
答案 0 :(得分:1)
像这样,根据需要更改工作表/列A:
Dim r As Range
Set r = ThisWorkbook.Worksheets(1).Range("A1").End(xlDown).Offset(1, 0)
DoCmd.TransferSpreadsheet acExport, , "Liste_factures_numero" _
, ThisWorkbook.FullName & Chr(35) & "Sheet1", True, r.Address
答案 1 :(得分:1)
你可以改变这个:
DoCmd.OpenQuery "Liste_factures_numero"
' Select answers
SendKeys "^a", True
' Copy
SendKeys "^c", True
对此:
DoCmd.OpenQuery "Liste_factures_numero"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
而且:
' Paste
SendKeys "^v", True
对此:
Cellule.PasteSpecial Paste:=xlPasteValues
另外,我必须补充一点,这是通过宏从Access到Excel实现此复制粘贴的另一种方法: