我已经找到了这个问题的几个答案,但是似乎没有一个对我有用。在我的主宏中运行的宏会生成需要复制到另一个Excel文件的值。但是我的主宏只是不等待生成完成,而是将空单元格粘贴到另一个文档中。基本上,宏会为我发布最终的excel文件,而宏仍在生成新值。如果我逐步运行该代码,则该代码按预期工作,但按run时则无法运行。
Set wbThis = ActiveWorkbook
strName = ActiveSheet.Name
Set wbTarget = Workbooks.Open("D:\Users\user37\Desktop\exportas\Information.xlsm")
wbTarget.Worksheets("Information").Activate
ActiveSheet.Range("B2").Value = myValue
Application.Run ("'Information.xlsm'!ExportData")
wbTarget.Worksheets("SO Lines").Activate
ActiveSheet.Range("E4").Copy
Set wbTarget = Workbooks.Open("D:\Users\user37\Desktop\exportas\Sablonai.xlsm")
wbTarget.Worksheets("Duomenys").Activate
ActiveSheet.Range("A1").Select
activeSheet.PasteSpecial
答案 0 :(得分:0)
由于性能问题,请尽量避免使用Activate
和Select
。当您逐步执行代码时,它应该可以按预期的方式工作,因为选择/激活能够在执行下一行之前完成。
尚未测试下面的代码,但我希望您理解With
的原理。
更多选择示例可以在How to avoid using Select in Excel VBA
上看到。Set wbThis = ActiveWorkbook
strName = ActiveSheet.Name
Set wbTarget =
Workbooks.Open("D:\Users\user37\Desktop\exportas\Information.xlsm")
With wbTarget.Worksheets("Information")
ActiveSheet.Range("B2").Value = myValue
Application.Run ("'Information.xlsm'!ExportData")
With wbTarget.Worksheets("SO Lines")
.Range("E4").Copy
End With
Set wbTarget = Workbooks.Open("D:\Users\user37\Desktop\exportas\Sablonai.xlsm")
With wbTarget.Worksheets("Duomenys")
With ActiveSheet.Range("A1")
.PasteSpecial
End With
End With
已更新:
'In case of multiple columns we create an array
Dim dData(1) as Variant
Set wbThis = ActiveWorkbook
strName = ActiveSheet.Name
Set wbTarget =
Workbooks.Open("D:\Users\user37\Desktop\exportas\Information.xlsm")
With wbTarget.Worksheets("Information")
'Copies column 1 and 2
data(0) = Application.Transpose(Range(Cells(1,1),Cells(1,1).End(xlDown)).Value2)
data(1) = Application.Transpose(Range(Cells(2,1), Cells(2,1).End(xlDown)).Value2)
End With
'Once again we copy the data from column 1 and 2
With wbTarget.Worksheets("SO Lines")
data(0) = Application.Transpose(Range(Cells(1,1),Cells(1,1).End(xlDown)).Value2)
data(1) = Application.Transpose(Range(Cells(2,1),Cells(2,1).End(xlDown)).Value2)
End With
答案 1 :(得分:0)
问题已解决,方法是转到生成宏->数据->连接并为每个查询禁用背景刷新