VBA Error?

ai1094

Board Regular
Joined
Aug 23, 2018
Messages
90
Hi, I have the following VBA code:

Set Wbk1 = ActiveWorkbook
Fname = "Path name"
Set Wbk2 = Workbooks.Open(Fname)
Wbk2.RefreshAll
DoEvents
Wbk2.Sheets(1).Copy , Wbk1.Sheets(Wbk1.Sheets.Count)
Wbk2.Close False

So basically this code is part of a macro that opens ANOTHER workbook which contains a macro and has power query that refreshes the tables to update the latest information. Then I copy the sheet from the second workbook into the first workbook. The issue is after the 'Wkbk2.RefreshAll' executes, it doesn't refresh with the latest information. However, when I run this part of the macro line by line it refreshes. What could be the problem?

Thanks
 

Some videos you may like

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes

jmacleary

Well-known Member
Joined
Oct 5, 2015
Messages
1,013
Office Version
365, 2007
Platform
Windows
Hello there. The difficulty is that vba refreshes don't always wait for the next line to be executed. Try this code wherever you want to be sure all database queries are complete:
VBA Code:
Application.CalculateUntilAsyncQueriesDone
So in your case you would put this on the line after the refreshall
 

ai1094

Board Regular
Joined
Aug 23, 2018
Messages
90
I'll give this a try, but where would I insert this line in the code? Also, do I need to remove any other lines of code?

Hello there. The difficulty is that vba refreshes don't always wait for the next line to be executed. Try this code wherever you want to be sure all database queries are complete:
VBA Code:
Application.CalculateUntilAsyncQueriesDone
 

jmacleary

Well-known Member
Joined
Oct 5, 2015
Messages
1,013
Office Version
365, 2007
Platform
Windows
VBA Code:
Set Wbk1 = ActiveWorkbook
  Fname = "Path name"
  Set Wbk2 = Workbooks.Open(Fname)
  Wbk2.RefreshAll
 Application.CalculateUntilAsyncQueriesDone DoEvents
  Wbk2.Sheets(1).Copy , Wbk1.Sheets(Wbk1.Sheets.Count)
  Wbk2.Close False
 

ai1094

Board Regular
Joined
Aug 23, 2018
Messages
90
It looks like this worked. Thanks a lot!

VBA Code:
Set Wbk1 = ActiveWorkbook
  Fname = "Path name"
  Set Wbk2 = Workbooks.Open(Fname)
  Wbk2.RefreshAll
Application.CalculateUntilAsyncQueriesDone DoEvents
  Wbk2.Sheets(1).Copy , Wbk1.Sheets(Wbk1.Sheets.Count)
  Wbk2.Close False
 

Subscribe on YouTube

Watch MrExcel Video

Forum statistics

Threads
1,105,930
Messages
5,508,173
Members
408,669
Latest member
AgsikapAko

This Week's Hot Topics

Top