Only paste last piece of code in column - vba

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.

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

Do While ActiveCell <> Range

I have this VBA excel macro code
Sub fillcells()
Range("J14").Select
Do While ActiveCell <> Range("J902")
ActiveCell.Copy
ActiveCell.Offset(6, 0).Select
ActiveCell.PasteSpecial
Loop
End Sub
At first it was working fine but now sometimes when I try to run the macro the loop suddenly stops at cell J242, other times is arising an error 'mismatch type' and sometimes the macro just select cell J14 without doing the loop
Not sure what you want to do, but (as noted in the comments to your OP), don't use .Select/.Activate. The following should do what (I think) you wanted:
Sub fillcells()
Dim i& ' Create a LONG variable to count cells
For i = 14 To 901 Step 6
Cells(i, 10).Offset(6, 0).FormulaR1C1 = Cells(i, 10).FormulaR1C1
Loop
End Sub
This will loop from cell J14 to J901, copy/paste* to a cell 6 rows offset.
* Note I didn't actually copy/paste. Since your original code used PasteSpecial, I'm assuming you just want the values pasted. In this case, you can set the two ranges/cells equal.
Just an addition to what #BruceWayne already said: whenever you have this typical phenomenon that something happens only "sometimes" it is often a case of using keywords such as Active or Current or Selection. These are not specific but change each time that you call the macro. Whatever you have selected is the starting point. You might even start clicking around and thus change Selection while the macro is running. In short, you should start coding explicitly and don't allow VBA / Excel to assume / make the decision for you.
Let's start with Range("J14").Select. This line of code asks VBA to make already two assumptions:
If you have several Excel files open. Which Excel file should it start with?
Within the file there might be several sheets. On which of these sheets should J14 be selected?
Explicit coding means that you (hopefully at all times) be very specific what you are referring to. So, instead of just stating Range("J14") you should use:
ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Range("J14")
But is pointed out in the other answer, this is not even necessary in this case. Rather loop the rows as shown and use:
ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Cells(i, 10).Offset(6, 0).Formula = ThisWorkbook.Worksheets("SheetNameYouWantToReferTo").Cells(i, 10).Offset(i, 10).Formula
Since this is a bit lengthy you can shorting it by using a With statement:
With ThisWorkbook.Worksheets("SheetNameYouWantToReferTo")
.Cells(i, 10).Offset(6, 0).Formula = .Cells(i, 10).Formula
End With

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

Vb excel loop not updating

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.

VBA Copy and Paste SQL Data as Values in Excel Spreadsheet Not Pasting

I have written a code which open a worksheet that contains a SQL data connection, I then refresh the data, copy the values and attempt to paste that information into the original spreadsheet.
the data does not paste, however, if i manually step through the code hitting F8 the data pastes - i can't figure out why this is -
if this is an easy question my apologies, I am new to VBA, I asked around my office and searched google - still can't find an answer - here is the code
Sub getdata()
'
' getdata Macro
'
' Keyboard Shortcut: Ctrl+a
'
' make holdings report tab visible and clear the contents
Sheets("Holdings Report").Visible = True
Sheets("Holdings Report").Activate
Range("A2:J65536").Select
Selection.ClearContents
' open the original holdings report, refresh data, copy data
Workbooks.Open "\\hcc-fileprint\sys\Share\Institutional Group\Rebalancing\HCNet Update.xlsm"
Sheets("Sheet1").Activate
Application.Wait Now + TimeValue("00:00:02")
ActiveWorkbook.RefreshAll
Application.Wait Now + TimeValue("00:00:02")
ActiveWorkbook.RefreshAll
Range("A2:J65536").Select
Selection.Copy
'activate the rebalancing spreadsheet paste the values and then hide the tab
ThisWorkbook.Activate
Sheets("Holdings Report").Activate
Range("A2").Select
ActiveSheet.paste
End Sub
Could it be that you're actually not copying anything, because the database query started with RefreshAll is running in the background and has not returned any data by the time you reach Copy?
I see that you're waiting 2 seconds, but that might simply not be long enough, whereas single-stepping gives Excel more time to get the data.
Unfortunately, there doesn't seem to be a specific event that you could react to when RefreshAll has completed, which would be the "right" way of going about it. Perhaps Workbook.SheetChange is fired though; you could try that.
Just a shot in the dark, really, but the copy/paste code itself doesn't seem wrong, and you didn't say that you get any errors.
Need to Modify the paste command to paste the values.
ActiveSheet.PasteSpecial xlPasteValues