Vb excel loop not updating - vba

I have the following code and what I try to do is basically collect data and locate that data in a cell starting from A1 up to A100 the data comes from cell M4 this particular cell is dynamic and is constantly changing it's value, is Pulling data from DDE
the code works but for some reason it takes the first value and does not update as the M4 is changing.
Any Ideas?
Sub looptest()
Dim loop_ctr As Integer
For loop_ctr = 1 To 100
ActiveSheet.Range("A" & loop_ctr).Value = Worksheets("sheet1").Range("M4")
Application.Wait (Now + TimeValue("0:00:01"))
Next loop_ctr
MsgBox " Done! "
End Sub

After Application.Wait ... line try adding:
DoEvents
As written, you code doesn't expose Excel to any other system events, like your DDE, to update the Excel application for the entire 100 second execution time of your loop.

Related

Getting vba to wait before proceeding

I need to update 4 different workbooks, which all collect data from bloomberg. I tried to construct a new workbook which will automatically open them and then the code within the workbooks will get activated since the code gets activated whenever the workbook opens. However my macro opens all workbooks at the same time and the update is taking too long when they are open at the same time. I tried to use the command "doevents" and "Application.Wait (Now + TimeValue("0:03:30"))", however they do not work. I would like them to open one at the time, then let the calculation in the specific workbook end before opening the next the next workbook.
Here is my code:
Sub UpdateWorkbooks()
'Quick Financial Longer Series
Workbooks.Open ("G:\FONDS\Quick financials_Longer Series.xlsb")
Application.Wait (Now + TimeValue("0:03:30"))
'Quick Financial
Workbooks.Open ("G:\FONDS\Quick Financial\Auto\Quick financials.xlsb")
Application.Wait (Now + TimeValue("0:03:30"))
'Quick Intra Corr (SX5E)
Workbooks.Open ("G:\FONDS\Quick Financial\Auto\Quick Intra Corr(SX5E).xlsb")
Application.Wait (Now + TimeValue("0:03:30"))
'SPX Sector Correlation
Workbooks.Open ("G:\FONDS\SPX Sector Correlation.xlsb")
Application.Wait (Now + TimeValue("0:03:30"))
Workbooks("UpdateWorkbooks.xlsb").Close savechanges:=True
End Sub
the application.calculationstate may help here. Wrap it up in a function, you could even return the state, and use a do until. Not sure of the infinite loop possibilities, so may be advisable to add a retry counter also.
Select Case Application.CalculationState
Case 0: strCalculationState = "Calculating"
Case 1: strCalculationState = "Done"
Case 2: strCalculationState = "Pending"
End Select

Only paste last piece of code in column

I am relatively new to this software and could really use a hand. I am using Ditta to store multiple items on a clipboard and have given them a shortcut. With this script I am trying to get it to paste all copied items at once, using a shortcut key. I have tested each block of code individually and it works. But when I try to run it together, it only runs the final block. Does anyone have any idea why this is happening?
Sub Data()
ActiveCell.Select
SendKeys "^4", True
Application.Wait (2000)
ActiveCell.Offset(0, 1).Range("A1").Select
SendKeys "^3", True
Application.Wait (1000)
ActiveCell.Offset(0, 1).Range("A1").Select
SendKeys "^2", True
Application.Wait (1000)
ActiveCell.Offset(0, 1).Range("A1").Select
SendKeys "^1", True
Application.Wait (1000)
End Sub
I don't know where exactly the issue is, but it seems that it is all about waiting for Ditto to insert the values. Your code is just not waiting until the paste is done.
I wrote a workaround for that:
We have a loop now that runs from 4 to 1 counting backwards (this is to send the 4 keys. This is easier than having 4 times the same code.
The main idea is to clear the cell before we paste, and after the paste we wait until the cell is not empty anymore, which means the paste was successful. Note this is just a workaround to wait an amount of time until the paste is done.
Option Explicit
Public Sub InsertData()
Dim i As Long
For i = 4 To 1 Step -1 'loop from 4 to 1 backwards
ActiveCell.Clear 'clear active cell (so we know it is empty for sure)
SendKeys "^" & CStr(i), True 'send keys for paste
'wait until active cell isn't empty anymore.
'this means wait until paste is done
Do While IsEmpty(ActiveCell)
DoEvents 'give Excel some time to handle other events
Loop
'move over to the next cell
ActiveCell.Offset(0, 1).Select
Next i
End Sub
Just a note to your original code
Your waiting was wrong anyway Application.Wait(2000) does not what you expect it to do. The correct way would be:
Application.Wait(Now + TimeValue("0:00:02"))
To make it wait 2 seconds. The given time is not the amount of time to wait but the absolute time until the macro waits. For more see Application.Wait Method.

Excel vba running differently on two computers

I am pulling my hair out over this as I cannot see why this isn't working. Any help or guidance would be greatly appreciated.
I have inherited a macro in Excel which runs differently depending on which PC we run it on. Essentially, the macro inserts blank rows into a table of data (which should also have conditional formatting to make it blue to break up the table and make it easier to read). On my PC instead of a blank row being entered, it is a row of #ref errors and loses the formatting.
We have a different macro assigned to a button which runs three macros one after another. The one I have the issue with is the third of these three. When I run the macros as three separate events it works, but together it has the #ref errors.
Sorry for the small snippet of the file, but it is sensitive information.
I have tried adding a pause in between the second and third, but this doesn't help.
Are there some security settings which I should check?
The macro looks at a formula in column A and looks for the number 5 and inserts a row after this line. The code is as follows:-
Sub Main()
Dim r As Range
Dim i As Long
i = 1
Do While Range("A" & i).Value <> ""
If Left(Range("a" & i), 2) = "5" Then
i = i + 1
Rows(i).Insert
Range("A" & i).Value = Range("a" & i - 1).Value
End If
i = i + 1
Loop
End Sub
What I am struggling to get my head around is that it works in isolation, but not when run with other macros. For completeness the macro which runs the three has the following code:-
Sub runall_CVR()
Application.ScreenUpdating = False
Call hiderows_CVR
Call Delete0s_cvr
Call Main
Application.ScreenUpdating = True
End Sub
Many thanks
James

Updating a chart while VBA is running

I'm trying to see visually what happens to a set of data in Excel each time I increment a driving variable by 1.
The data is visualised in a chart and the increments are done via a for-next loop on an integer n.
Each time I increment n, the values in a table update and the chart should update too. Except it doesn't. The table updates but the chart waits to the end of the routine and shows its position for the last value of n only.
I have put a wait command in, tried Charts("Chart 1").Refresh etc but the chart won't update (albeit the table feeding it does) during the intermediate steps of the code as I'd like it to. I'm on automatic calculation so its not that that's causing the problem.
How do I get the chart to update to the table values whilst the code is running. This was the code sorry.
Sub Walkthrough()
Dim n As Integer
For n = 0 To 77
Range("L3").Value = n
Application.ScreenUpdating = True
ActiveChart.Refresh
Application.Wait Now + #12:00:01 AM#
Next n
End Sub
This is how to make it workable:
Option Explicit
Sub Walkthrough()
Dim n As Long
Application.ScreenUpdating = True
For n = 0 To 5
Range("a1").Value = n
Application.Wait Now + #12:00:01 AM#
Next n
End Sub
Make sure that A1 is your dependent range in the example. By default the Application.ScreenUpdating is set to True in Excel, thus you do not need to set it explicitly.
I had success by activating the chartObjects in the ActiveSheet. However, I am not 100% sure about the DoEvents calls. Excels selection behavoiur was a bit strange after the procedure finished. Propably because a ChartObject was still activated. Therefore, I finally activate the ActiveSheet.
Option Explicit
Sub Walkthrough()
Dim myChart As ChartObject
For Each myChart In ActiveSheet.ChartObjects
myChart.Activate
DoEvents
Next
ActiveSheet.Activate
DoEvents
End Sub

Pause VBA code without pausing spreadsheet

I have a VBA code where it is copying and pasting data from a spreadsheet that pulls data from an external server. Consequently, that spreadsheet takes awhile (from 10-30 seconds) to load the data.
I have researched how to pause a macro - application.wait, sleep, etc - but they also pause the spreadsheet functions so the data from the external server cannot load. Therefore when the code copies the data, it pastes #DIV/0!. Is there a function that can interrupt/stop/pause the macro to give the server data time to load?
I also would like this macro to run without needing user input (some suggestions online had the user advancing the code each iteration).
Sub all()
Dim wb1 As Workbook
Set wb1 = Workbooks("all")
Dim wb2 As Workbook
Set wb2 = Workbooks("other")
For i = 2 To 5
Application.Wait Now() + TimeValue("00:01:00")
wb2.Sheets("Sheet1").Cells(4, 2).Copy
wb1.Sheets("Sheet1").Cells(i, 18).PasteSpecial xlPasteValues
Next i
End Sub
Application.Wait suspends processing in Excel. This means that your background processing will suspend, too.
Instead, try this:
Dim WaitTime as Date
For i = 2 To 5
WaitTime = Now() + TimeValue("00:01:00")
While Now() < WaitTime
DoEvents
Wend
wb2.Sheets("Sheet1").Cells(4, 2).Copy
wb1.Sheets("Sheet1").Cells(i, 18).PasteSpecial xlPasteValues
Next i