I am running a macro and one iteration of a While loop in the macro does not complete all of the calculations before data is copied and pasted into another tab. So incorrect data is copied and pasted in the subsequent step. Is there a way to force these calculations to occur? Is this a memory issue?
The calculations in question always complete immediately after the Macro finishes and are no different than the calculations that occur in prior iterations of the loop.
I have tried:
Do While Not Application.CalculationState = xlDone
If Application.CalculationState = xlPending Then Application.Calculate
Application.Wait (Now + TimeValue("00:00:02"))
Loop
As well as other versions of this paradigm trying to force calculations to complete prior to proceeding to the copy and paste section for each iteration.
Edit:
Sub Pull_Portfolio_Collateral()
Dim i As Integer
Dim portfolio_rows As Integer
Application.ScreenUpdating = False
portfolio_rows = GetSizePortfolio() + 1
Dim template As Worksheet
Dim portfolio As Worksheet
Dim full_coll_list As Worksheet
Dim individual_list As Worksheet
Dim row_cnt_tmp As Integer
Set portfolio = ActiveWorkbook.Sheets("Portfolio")
Set template = ActiveWorkbook.Sheets("Security - Deal Collateral")
Set full_coll_list = ActiveWorkbook.Sheets("Full Coll List")
For i = 2 To portfolio_rows
'Set Template sheet
template.Copy After:=Worksheets(Sheets.Count)
If portfolio.Range("B" & i).Value <> "" Then
'Rename Newly created sheet and set the CLO security name
On Error Resume Next
ActiveSheet.Name = Left(portfolio.Range("B" & i).Value, 12) & " - Coll"
Set individual_list = ActiveWorkbook.Sheets(ActiveSheet.Name)
individual_list.Range("E3").Value = portfolio.Range("B" & i).Value
'Wait for Application to Calculate before pasting
Application.Calculate
Do While Not Application.CalculationState = xlDone
DoEvents
Loop
'Identify the Last Row and copy it to clipboard, then paste in full collateral sheet
row_cnt_tmp = individual_list.Range("O2").Value
row_cnt_tmp = row_cnt_tmp + 7
If i = 2 Then
full_coll_list.Range("B2:V100000").ClearContents
individual_list.Range("D8:X" & row_cnt_tmp).Copy
full_coll_list.Range("B2").PasteSpecial xlPasteValues
Else
individual_list.Range("D8:X" & row_cnt_tmp).Copy
full_coll_list.Range("B" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
End If
End If
template.Activate
Next i
individual_list.Range("D8:X" & row_cnt_tmp).Copy
full_coll_list.Range("B2:V").PasteSpecial xlPasteFormats
MsgBox "End Pull Collateral"
End Sub
Where the function GetSizePortfolio() is:
Function GetSizePortfolio() As Integer
Dim rng As Range, n#, b#
Set rng = ActiveWorkbook.Sheets("Portfolio").Range("B2:B1000")
On Error Resume Next
b = WorksheetFunction.CountBlank(rng)
n = rng.Cells.Count - b
On Error GoTo 0
MsgBox "The number of non-blank cells in column " & col & " is " & n
GetSizePortfolio = n
End Function