Excel VBA - Copy and Paste each cell Individually to another program - excel

I'm fairly new to VBA but know my way around it a bit (sorta). What I'm needing to do is get a Macro set to copy data in one cell, switch to another program (2315), enter "6", [ENTER], paste the data, [ENTER] switch back to Excel, select the next row, copy, switch, paste, switch, until it reaches the end of the column. This is what I have, which works for the first cell. I just need to figure out how to loop it until it reaches the end. Thanks for any help/suggestions!
Range("A2").Select
Selection.Copy
AppActivate "2315"
Application.SendKeys "6~^V~"
Application.SendKeys "%{TAB}"
Thanks Again!

I doubt that this works, but you say it does and your question is about the loop. Here is the loop.
Dim R As Long
For R = 2 To Cells(Rows.Count, "A").End(xlUp).Row
Cells(R, "A").Copy
AppActivate "2315"
Application.SendKeys "6~^V~"
Application.SendKeys "%{TAB}"
Next R
For Excel's sake you don't need to select anything. The above code will loop through all the used cells in column A of the active tab. If your app "2315" needs the selection, add Cells(R, "A").Select before the copy instruction.
My doubt is based in the fact that you can't use VBA to send parameters to app "2315". This includes the instruction to "2315" to surrender control back to Excel and its VBA. Perhaps you have found such a way via the SendKeys. If so, the code will work. If not, it will get stuck after the first loop.
Logically, the code should run until AppActivate "2315", meaning the SendKeys are never sent until the other app has returned control. If that is what's going on there must be better ways to express whatever your two instructions get done. But that shouldn't be your immediate concern. If you can get "2315" to surrender control back to Excel with a simple command like Enter, and if the above macro really resumes work where it left off, most of your problem should be solved. This I hope for :-)

Related

I need a VBA code that after Userform enters date into a database, refreshes the cell the same way as going into it and pressing enter does

I have a long chunk of code that handles date data from a hidden datasheet, however anytime I enter a new date trough a userform, it writes it into the cell in the database in a format that for some reason can't be handled error free by my code chunk.
The problem is I need a sub to change the format (which is easy) but it does not actually apply the formatting unless I manually go into the datasheet, enter the cell and press enter.
I have searched and could not find a solution on how to do this in VBA, obviously this code is supposed to run automatic flawlessly plenty of times and having to manually go in an enter the cell defeats the entire purpose of the programming.
Sub Testing123()
MsgBox "run"
Workbooks("Excel Stock System.xlsm").Worksheets("DataNews_Events").Columns(8).NumberFormat = "dd.mm.yyyy hh:mm"
'something magic that actually automatically applies the format
End Sub

Range.ClearContents interferes with a paste macro

Hi I have a question about clearing and pasting a selection from another workbook.
I am trying to make a macro that clears the old data I have in a tab and copies the data I have on my clipboard from another excel workbook in it's stead.
I kept getting an error before I noticed what was wrong. When the macro runs the clearing part, it cancels my selection/copy data I had, so the pasting part does not work. does anybody know how to circumvent it? I can't reference the excel where the data is coming from directly because it varies every time.
the code I use now for the clearing:
Sub clearData()
Worksheets("ZRFI08TW").Range("A5:M5000").ClearContents
End Sub
The coded i use now for the pasting of the data (i know its not the best, but trying different things before i noticed the conflict ended up with this one):
Sub copyData()
ActiveSheet.Range("A5").Select
SendKeys "^v"
End Sub
I can come up with two options, following the logic of your code for using SendKeys "^v" for a paste:
Using - Worksheets("ZRFI08TW").Range("A5:M5000") = ""
Assigning the Selection to a range and then selecting this range again and pasting it:
Dim myRange as Range
Set myRange = Selection
Worksheets("ZRFI08TW").Range("A5:M5000").ClearContents
myRange.Select
myRange.Copy
ActiveSheet.Range("A5").Select
SendKeys "^v"
But there should be a way better way to achieve what you are looking for. And as I am mentioning .Select, I feel an urge to mention this one - How to avoid using Select in Excel VBA.

Most efficient way to remove all linebreaks in worksheet

I have a macro which iterates over column C, anytime the cell is not empty it opens a file referenced in Column B, searches this newly opened file for a string that is written in column A and then replaces the content of that cell with what is written in column C. My problem though is that in the newly opened file, there are line breaks in some columns (sometimes trailing, sometimes where there should only be a space), so the macro doesn't find the right cell.
I was thinking to solve this I write another macro which goes through those files and replaces every line break with a space. It's basically just
For Each Cell In Worksheet.Range(Cells.Address)
Cell.Value = Replace(Cell.Value, Chr(10), " ")
Next
This seems to work, but I can't run it without excel crashing. Are there more efficient ways to do this? Or maybe all together a better approach to my problem? Thanks.
The VBA DoEvents function temporarily pauses a running macro, giving Excel a chance to process key presses, mouse clicks, and other operating system messages.
In long-running macros, Excel can appear to hang and become unresponsive, and the macro may be impossible to interrupt. If DoEvents is included in your code, users can be assured that the macro is still running, and can still interrupt execution if necessary.
For Each Cell In Worksheet.Range(Cells.Address)
Cell.Value = Replace(Cell.Value, Chr(10), " ")
DoEvents
Next
Source: automateexcel
This (I hope) is an implementation of BigBen's suggestion for the active sheet:
Sub test()
Dim r As Range
Set r = ActiveSheet.Cells.SpecialCells(xlCellTypeConstants)
r.Replace Chr(10), " "
End Sub
EDIT#1:
The code above relies on the proper worksheet being Active. A safer alternative would be to use something more explicit like:
Set r = Sheets("my data").Cells.SpecialCells(xlCellTypeConstants)
NOTE:
We are using the .Replace() Method rather than the Replace() function.

Waiting for user input - with DoEvents a good idea?

My macro is going to compare a sheet with another sheet. This second sheet needs the user to paste data in there. (Note: The data being copied is not in Excel).
One way is to run the macro, and end it by prompting the user to paste the data in, then run "Macro2". However, I'd like to keep it all in one macro, so have found a way to wait for user input before continuing. This seems to work for me, so my main question is:
How stable is doing it this way?
...macro stuff above here
MsgBox ("[Please copy the data into the new sheet, after clicking 'OK']")
Do While WorksheetFunction.CountA(newWS.Cells(1, 7)) < 1
DoEvents
Loop
...then after the user pastes info, continue on, using the data that's been pasted.
The idea is that DoEvents just runs and runs while my sheet is blank. Right after the user pastes the data into the newWS, the macro continues on (since it will see data in column 7)...
Is this an okay method, or is it a bad idea to use like that? I've never really used DoEvents, so don't know if it's doing something in the background that could cause issues.
Edit: The data is in Lotus Notes, which I can export to Excel. However, that takes a few more steps (and I'd rather not create some new temporary excel files), so copy/pasting is my preferred method. This question is half practical, and half theoretical. Sorry for any confusion!
Probably not the best idea. Instead, allow them to select the data and perform the copy, all through VBA:
MsgBox ("[Please select data to copy into the new sheet, then press 'OK']")
newWs.Cells(1,1).PasteSpecial '### Modify to your specific location to paste the data
'Here you can add logic to validate that they have pasted enough data,
' and use control statement to prompt them to paste more data, etc.,
' if necessary, or exit sub early
'For example:
If WorksheetFunction.CountA(newWS.Cells(1, 7)) < 1 Then
MsgBox "Try again!"
Exit Sub
End If
Alternatively, you can use a DataObject:
Dim dataObj As New MSForms.DataObject
dataObj.GetFromClipboard
newWs.Cells(1,7).Value = dataObj.GetText
You could restructure the code so that it lives inside of a userform with ShowModal set to false (in the properties). Code prior to when you want the user to gather data can be put in the useform's initialize event. Then the userfrom shows (with a simple label caption and an okay button). Since it is modeless the user can copy data from an external program and paste it in. Then the rest of the code runs after the user hits okay. The form itself can be hidden during this phase. As proof of concept I created the following form:
with the following code:
Private Sub CommandButton1_Click()
Me.Hide
MsgBox Range("A1").Value
Unload Me
End Sub
Private Sub UserForm_Initialize()
'macro code can go here
'it runs before the form shows
'e.g.
MsgBox "Initializing"
End Sub
I launch the form on a blank sheet. First a message box appears before the code (confirming that code can run while the form is being initialized but before it is visible) then the form shows:
I go to an open instance of Notepad which contain a sentence and, while the form is still open -- paste it into A1:
Finally I press okay and the userform then hides itself but continues to run code (which now has access to the copied data):
Remember to unload the form at the end.

How to copy-paste from DOS application to Excel using SendKeys?

I'm trying to simulate this action:
activate another application,
send keystroke ctrl+c,
go back to Excel,
send key stroke ctrl+v
and have that value in a cell.
It's a DOS window style application, so keystroke is the only way to manage it.
I managed to activate and to input keystrokes such as ENTER into that DOS style application, but when I try ctrl+C it is not seen to do anything.
I tried simulating it in Excel VBA with:
Range("E7").Select
SendKeys "^c"
Range("G7").Select
SendKeys "^v"
The E7 value is not copied, but G7 (paste destination) is highlighted as if it was selected for copying.
Note: I am not trying to copy things from Excel to Excel, but to execute keystrokes using Excel.
I ran into the same issue today.
I solved it by waiting a bit after sending CTRL-C to the application. It seems nothing is copied if you immediately execute another script line.
SendKeys "^c"
WScript.Sleep 100 ' wait a bit after CTRL+C (otherwise nothing is copied)
In fact, the same issue seems to happen when switching to another app and sending CTRL+V.
Again, I solved it by waiting a bit:
AppActivate "Microsoft Excel"
WScript.Sleep 100 ' wait a bit after making window active
SendKeys "^v"
The problem is that copying and pasting takes some time and VBA is not waiting for it.
First you need to specify second argument of send keys method which is "Wait". Set it to true. Thus VBA execution is waiting for until sending keys is completed.
Secondly you need to wait until process of copying data to clipboard is completed. "Wait" in sendkeys is not doing it because it's not about sendking keys by VBA but it's about Windows working with clipboard. To do it please use my function IsCopyingCompleted.
Here's how final can look like:
SendKeys "^a", True 'Select all
SendKeys "^c", True 'Copy
Do
DoEvents
Loop Until Me.IsCopyingCompleted()
YourSheet.Paste
Function IsCopyingCompleted() As Boolean
'Check if copying data to clipboard is completed
Dim tempString As String
Dim myData As DataObject
'Try to put data from clipboard to string to check if operations on clipboard are completed
On Error Resume Next
Set myData = New DataObject
myData.GetFromClipboard
tempString = myData.GetText(1)
If Err.Number = 0 Then
IsCopyingCompleted = True
Else
IsCopyingCompleted = False
End If
On Error GoTo 0
End Function
I had this same problem - I developed code and it worked on my computer - SendKeys "^v"...but it did not work on another user's computer! I was trying EVERYTHING...delays, appreciate, accessig access from Excel, having the user check various settings, selection.paste...no good. Finally I noticed different syntaxes...we were using the same office version, I'm not sure about Windows. But I entered 6 different syntaxes and had it skip over if it failed....SendKeys with a capital v, enclosed in squigley brackets, each component in squigleys separated by a plus sign, etc. IT WORKED! 2 of the commands put the ^V in the body of outlook...I remove those 2 and I'm golden.

Resources