Range.ClearContents interferes with a paste macro - excel

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.

Related

Is there a way using sheet protection to allow a user to enter values but protect formats?

I have a worksheet containing a column of numbers. The column is formatted with a background color, number formats, etc. The column is unlocked. I protect the sheet manually by right-clicking on the tab and selecting Protect. In the Protect Sheet dialog, 'format cells' is unchecked. I interpret to mean that the user should not be able to format cells. Yet when the user pastes into the column, formats are pasted along with values.
If I protect the sheet in VBA using
sh.Protect UserInterfaceOnly:=True
I get the same result: formats are pasted. I do not specify AllowFormattingCells:=False because the default is False.
I have seen posts suggesting that formats can be restored by copying and pasting them from a shadow area. I have used this solution before I started protecting worksheets and found it overly complex. I had hoped this was something protection would handle. If there is a way to handle it, I'd like to do it in VBA.
This question is a little old, but I had the same one, and so have many people in the past. With a bit of browsing I came up with a solution which seems quite clean and appears to work. Am I missing something?
Private Sub Worksheet_Change(ByVal rngTarget As Range)
Dim vPaste As Variant
With Application.CommandBars("Standard").Controls("&Undo")
If Not .Enabled Then Exit Sub
If .ListCount < 1 Then Exit Sub
If .List(1) <> "Paste" Then Exit Sub
End With
vPaste = rngTarget.Value2
On Error Resume Next
Application.EnableEvents = False
Application.Undo
rngTarget.Value2 = vPaste
Application.EnableEvents = True
On Error GoTo 0
End Sub
This could go in Workbook_SheetChange, but not if you already have code in Worksheet_Change, because the worksheet event handler gets called before the workbook event handler. But this code can go in a module to keep things tidy.
There is no built-in protection option you can use to achieve your desired result.
The only thing that works in this case is the clunky workaround that you mention, i.e. use a Worksheet_Change event that ensures the correct format after a cell has been modified.
Since there are many different ways to paste content, i.e. via various menus, ribbon commands, keyboard shortcuts, etc., any VBA solution that tries to intercept pasting will become very complex, much more complex than the change event that restores the format to its original state.
Another option might be user education and training (so they know to paste values only), although user behaviour may be the toughest element to change in the whole scenario.

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

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 :-)

How To: Let users paste cells from another excel instance (Ctrl+V,...) but paste only values

EDITED WITH PROGRESS
Dear Stackoverflow community,
I am working on a big excel file that does some calculations for me and my colleagues. Because the calculation data is a lot and is entered in Ranges (like "A1:H8"), not single cells (like "A1","C1",...), I want the users to be able to copy data from the same or another excel instance to my file.
The problem (edited):
The problem is, that just pasting cells formats the target cells (even if they are protected against formatting) and this has to be avoided. I searched through a lot of online discussions and finally made my own code, that allows me to copy and paste between two excel files in the same excel instance. Sadly, it does not work, if I copied the cells from another instance.
The code:
This is the code I use in "ThisWorkbook":
Sub PasteValuesOnly()
'if cells are pasted in named worksheets, only values are pasted
'is linked to Ctrl+V in options of macro menu
On Error GoTo err_handler
Dim Target As Range
Set Target = Selection
If Target.Parent.Name <> "Table1" Then
Selection.PasteSpecial
Else
Selection.PasteSpecial Paste:=xlPasteValues
End If
err_handler:
Exit Sub
End Sub
The system:
Windows 7
Excel 2010
What I tried besides my code (new progress):
As mentioned in the comments, I know Siddharth Rout's solution for only letting the users paste values, but I can't get it to work (not even in a fresh file when copying and pasting inside one Excel instance). I tried it for the whole workbook and for one single sheet.
What would help (edited):
It would be very helpful, if you could tell me how to optimize my code, so it works for two instances as well. If you know what is to do when I have an error with UndoList = Application.CommandBars(“Standard”).Controls(“&Undo”).List(1) in Siddharth Rout's solution with Excel 2010, this would be helpful, too.
Otherwise I would like every solution, that let's my users paste like they ever do, but prevent them from formatting the cells while pasting.
Thank you in advance
RaspiManu
After long hours of searching the internet, I found the solution of Donna Landy (Bella_Donna) in the microsoft forum. Her code is simple and works for CTRL+C / CTRL+V, Copy and Paste over Right Click Menu, Drag'n'Drop and even with two excel instances.
Because it starts on every single cell change and goes back to the cell or range that was changed, I slightly optimized it for my needs. Now, users that enter a list manually won't have to press "Enter" two times every time, they want to get to the next line below.
Assuming, the standard user will normally copy and paste, if there is a range of data, he or she does not want to retype, I changed the code, so the module sub only gets activated, if more than one cell has been changed (see below).
The solution:
In every worksheet, that has to be protected against formatting (modified):
Private Sub Worksheet_Change(ByVal Target As Range)
'activates format protection when changing a range
If Target.Cells.Count > 1 Then 'If more than one cell has been changed...
Call Worksheet_Change_Protected(Target) '...activating protection
End If
End Sub
In a module (unmodified):
Sub Worksheet_Change_Protected(ByVal Target As Range)
'Prevents user blithely obliterating in-cell formatting by undoing their paste and pasting the value
'Donna Landy 26.11.2018
'May be freely copied - hat tip appreciated :)
Dim SavedVal As Variant
On Error GoTo ErrHan
'Save the pasted value for later
SavedVal = Target.Value
'Switch off events to prevent infinite loop
Application.EnableEvents = False
'Undo the user's paste
Application.Undo
'Set target value
Target.Value = SavedVal
ErrExit:
'Remember to re-enable events
Application.EnableEvents = True
Exit Sub
ErrHan:
Resume ErrExit
End Sub
Thank you very much, Donna Landy!

Why is defined range not working with End(xlDown).Select?

I am running a function with a defined range and when trying to use End.(xlDown).Select I get a message "Select method of Range class failed".
I have edited the code below to show only the problem piece. After literally two hours of trying everything, I cannot get it to work.
The annoying part is that I have to use defined ranges since the function is part of a much larger Sub that doesn't work as intended once Select and Activate are used.
Function OutputFunction()
Dim rng8 As Range
Set rng8 = ThisWorkbook.Worksheets(5).Range("A2")
rng1.ClearContents 'Works like a charm.
rng2.Copy 'No problem here either.
rng8.End(xlDown).Select 'Fails misserably.
ActiveCell.Offset(0, 13).Select
Range(Selection, Range("N3")).Select
ActiveSheet.Paste
rng2.Copy destination:= rng8.parent.range(rng8.End(xlDown).Offset(0, 13), rng8.parent.Range("N3"))
"After literally two hours of trying everything, I cannot get it to work."
The first rule of Excel Macros: Never, ever, use SELECT in an Excel Macro.
The second rule of Excel Macros: Don't use Select in Excel Macros
The third.....
Try:
Option Explicit
Sub test()
Dim rng8 As Range
'Have in mind that you refer to a sheet based on it s index, NOT with its name!
'If sheets order change you will refer to another sheet
With ThisWorkbook.Worksheets(5)
Set rng8 = .Range("A2")
rng8.Select
.Range(rng8, rng8.End(xlDown)).Select
End With
End Sub
Try to use End(xlDown).Select in my personal macro. First I tested this in the original excel file that I wrote the macro in, and it worked in every step just fine. But the problem occurred when I used it in another file.
After some tests, I changed the .Select with .Activate and it worked. I'm not 100% sure whether we are talking on the same page or not, so tell me if this solved your problem, so I can improve my answer.

Copy/Paste data to other existing workbook on timer

I currently have this VBA -
Sub StartTimer()
Application.OnTime Now + TimeValue("00:00:15"), "AutoCalc"
End Sub
Sub AutoCalc()
Application.CalculateFull
Sheets("Kine").Range("B603:E603").Copy _
Destination:=Workbooks("AutoImportAverages.xlsx").Worksheets("AvgKine").Range("B1:E1")
Application.OnTime Now + TimeValue("00:00:15"), "AutoCalc"
End Sub
The .OnTime command is working perfectly without the Copy/Paste section, which is great.
This gives me a list of values from an SQL query that will auto-update, as well as an average at the bottom of each column of values.
I'm trying to set this up so that the average will automatically be added onto columns in Minitab but I believe that the Macro is stopping the Auto-Update in Minitab.
So my idea is to copy-paste the averages into an Excel Workbook that has no macros of its own and then link that to Minitab.
Have I put in the Copy-Paste code wrong or is there some issue with where the macros need to be stored and how?
Quick Edit - I should add that current code gives "Run-Time Error 9, Subscript out of range" and highlights copy/paste code.
I've found the solution.
My destination workbook was open in a separate window so the source wasn't recognising it as being open. Bit of a nightmare!
It's necessary to have both workbooks open in the same instance of Excel.
Additionally, my original paste code only pasted "#REF". I have changed that to -
Workbooks("AutoImportAverages.xlsx").Worksheets("AvgKine").Range("B1:E1").PasteSpecial xlValues
Works much better.
One more thing, in case anybody might find it useful. The source workbook must be active in order to carry out the auto-update.
Adding below line sorted out most issues though its still a work in progress -
ThisWorkbook.Activate

Resources