copy text from one excel to another one - excel

I would like to copy the text from a excel file in a specify range to another excel file in the same position
Here is the code that I tried
Sub OneCell()
ChDir "C:\Workfile"
Windows("simple av & cv template(Level).xls").Activate
Sheets("Table ENG SG").Select
Range("C9:C44").Select
Selection.Copy
Windows("Finalize").Activate
Sheets("sheet1").Select
ActiveSheet.Paste
End Sub
Do I need to define sth at the beginning of my program first or did I make any mistakes?

Assuming both your workbooks are open in the same instance of Excel which you can confirm by going to the View tab > Switch Windows and seeing if both workbook names are listed:
Sub ModifiedOneCell()
Workbooks("simple av & cv template(Level).xls").Sheets("Table ENG SG") _
.Range("C9:C44").Copy _
Destination:=Workbooks("Finalize").Sheets("sheet1").Range("C9:C44")
End Sub
The help for this can be found by opening the Object Browser in VBA (press F2), scrolling down to the Range object, clicking Copy from the list in the right pane then press F1.
The [space][underscore at the end of lines is the line continuation key combination in VBA allowing you to split long lines of code for readability.
If your workbooks are open in separate instances of Excel (i.e. only one is visible in Switch Windows), then copying to the clipboard and selecting Windows as you did in your code is the correct approach.
You would need to add
Range("C9:C44").PasteSpecial xlPasteAll
in place of
ActiveSheet.Paste
to get the result into the desired range
Ranges don't have a Paste method - only PasteSpecial.

Related

Macro Paste in Excel

Currently I have macros set up in my excel that pastes a list when clicked.
However I am encountering an issue where I have to paste the copied list (from a pdf) into notepad before pasting into excel, so that it separates into cells instead of trying to excel cram the entire list into one cell when done directly.
I have tried creating a macro that would open a cell directly paste into it then cut out before pasting (Which works when done manually) as well as a number of different methods that were all dead ends.
My procedure is currently:
Open PDF, ctrl a, ctrl c
paste into notepad then ctrl a, cut
paste into excel
If I could get help removing the notepad part of the procedure, I would be incredibly happy!
If you paste the whole thing inside a cell like this:
Then you can use this script to do a text to rows operation.
Option Explicit
Sub TextToRows()
Dim RG As Range
Dim RGValue As String
Dim LinesArray
Dim LineCount As Long
Dim I As Long
Set RG = Selection
If RG.Cells.Count <> 1 Then Exit Sub
RGValue = RG.Value
LineCount = Len(RGValue) - Len(Replace(Replace(RGValue, Chr(13), ""), Chr(10), "")) + 1
If InStr(1, RGValue, Chr(10)) = 0 Then
LinesArray = Split(RGValue, Chr(13))
Else
LinesArray = Split(RGValue, Chr(10))
End If
RG.Offset(1, 0).Resize(LineCount, 1).Value = Application.Transpose(LinesArray)
End Sub
Viola!
Your aim is reduced notepad step however I suggest I would remove the pdf step since poppler or xpdf pdftotext -layout is usually good to add the needed white space to keep text tabular. That can be drag and drop pdf on a shortcut that calls open new spreadsheet with text. And here is the usual core issue with cut and paste plain text as a framework.
Most spreadsheets as far back as last century have several text import methods, most common is add commas for csv import, but space separated text is accepted too. (I still use MSeXcel 97 portable as its an old familiar) It often requires some intervention to check detection, so here in Modern Open Office I specified combine spaces. Thus, introduces just one minor error here, "Addresss" is moved left-wards.
No Problem it has a spelling mistake so it's just that one that needs managing twice. 1st spell check and then move it right.
Every case can be different but if you write a macro to cover those corrections you repeat then it pays to run for the next import to include all the steps.
The simplest is plan ahead by tidy the text (here used tabs to replace spaces), then drag and drop, the results are usually cleaner data in = cleaner the cells are aligned.
Thank you everyone for your advice, I finally found a solution. It was as simple as a paste special text.
ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
Hopefully this helps someone else! Found it whilst looking into ways the window operating system formats copy/paste. It can be manually done by right clicking > Paste Special > Text

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!

VBA .SetText and .PutInClipboard putting two symbols in clipboard instead of desired data

Using Excel 2016 and a reference to the Microsoft Forms 2.0 Object Library, I'm trying to copy the ActiveCell's contents to my clipboard. Instead, the resulting contents of my clipboard are the following 2 symbols (if they'll actually show up in this text field.
��
��
(In case those symbols aren't rendering, in the StackOverflow website's text editor they look like white rectanges. Depending on the text editor I'm pasting it in, they've also resembled a question mark, a black diamond containing a white question mark, and just a blank space as if the space bar was pressed.)
I'm not trying to copy symbols of any kind, it's plain English. I've used code similar to this in other macros and it's always worked until today. The code itself is below. I hope you can help!
Dim clipboard As New MSForms.DataObject
clipboard.SetText ActiveCell.Value
clipboard.PutInClipboard
Debug.Print clipboard.GetText(1)
Set clipboard = Nothing
The Debug.Print command prints out the desired text, but after the macro finishes, the desired text is not there and instead there are the 2 symbols again.
In Windows 10, if file explorer is open the putinclipboard does not work. Go figure.
https://www.mrexcel.com/board/threads/copy-cell-address-to-clipboard-issue-putinclipboard-not-working.983442/
One way that worked for me is;
-Close Excel and File Explorer.
-Reopen Excel test the functionality of PutInClipboard /paste
-Open Window 10 File Explorer
-Test again.
*I work for me why? I don't know but it seems that excel has to be open prior to File Explorer.
The effect seems version dependent, whether the explorer window is opened before or after Excel. It also depends on what is in the explorer window - if it is a 'system location' such as "This PC", then putinclipboard still works normally.
I had tried various options for ages, but eventually found one workaround - acting as if copying manually...
In this case, the text to be copied to the clipboard is in the active cell, but the approach can be adapted for other circumstances:
Sub AACopyText() 'has to be called from Excel workbook (ie not from the VB window!)
SendKeys "{F2}^a^c{ESC}"
End Sub
F2 activates the contents of the cell, ^a selects the entire contents, ^c copies the contents to the clipboard; {ESC} is then required or the cell contents remain active.
if the required text is not the activecell content, for example is in a variable eg MyTextToCopy then the activecell can be temporarily over-written:
AppActivate ActiveWorkbook.Name
SendKeys "{F2}^a" & MyTextToCopy & "^a^c{ESC}"
These lines activate the activecell in the active workbook (so can be used in a procedure called from a form, etc), selects the contents, overwrites the contents, copies the new contents, then returns the original contents.
Alternatively, use can be made of Notepad; the following routine will work in programs other than Excel:
Function clip(ClipText As String)
On Error Resume Next
Dim WasntOpen As Boolean
AppActivate ("Notepad")
If Err Then
WasntOpen = True
Err.Clear
x = Shell("Notepad.exe", vbNormalFocus)
AppActivate ("Notepad")
End If
SendKeys "^a" & ClipText & "^a^c^z"
If WasntOpen Then SendKeys "%Fx"
End Function
where 'ClipText' is the text you want to save
eg In your routine, the line
Clip("1234")
will put "1234" on the clipboard

Copy paste shapes from cells

I have made a code that creates labels and barcodes for printing.
Due to other reasons (for simplicity) I have placed some labels on a separate sheet that I then need to transfer to the real sheet.
I found some mention about the CopyObjectsWithCells but it's not working for me.
Application.CopyObjectsWithCells = True
Sheets("Robot").Range("A1:L" & Lastrow).Copy
Sheets("Etikett").Range("A" & intRad).PasteSpecial Paste:=xlPasteAll
I get the same result Range().Select then Selection.Copy.
Sheets("Robot").Shapes.SelectAll
Selection.Copy
Works. But it makes the pasted image one large image, not x small images/shapes. and gives a white background overlaying the other text on the sheet.
If I select the range in Excel and press Ctrl + C / V it copies the images as I want.
But with VBA it just won't work.
Example image
Whenever you have a problem, which is can be described with:
I have managed to do it manually in Excel, but I cannot find the correct VBA code.
a good solution is to use the macro-recorder option in VBA and see the code it generates, while you do the manual work in Excel. In your case, this is the code it makes, when it simply copies two shapes to another worksheet:
Sub Makro2()
ActiveSheet.Shapes.Range(Array("Rectangle 1")).Select
ActiveSheet.Shapes.Range(Array("Rectangle 1", "Rectangle 2")).Select
Sheets("Tabelle2").Select
Range("B4").Select
ActiveSheet.Paste
Range("M25").Select
End Sub
This code is really bad, but it works and it may give you good insights to work further.
After selecting and copying the range that contains the shapes, select the destination cell and then use ActiveSheet.Paste.
The option you are using PasteSpecial Paste:=xlPasteAll won't paste Shapes.

how to use the following excel vba code?

Sub MergeRanges()
Dim rng As Range, txt As String
For Each rng In Selection
txt = txt & rng.Value2
Next
Application.DisplayAlerts = False
Selection.Merge
Selection = txt
Application.DisplayAlerts = True
End Sub
when merge cells, i want to remain all the data in the cells. i googled some time,finding the above code. but i don't know how to use it? and what's the meaning of them. thank you.
Setup:
Open VBA editor (Tools > Macro > Visual Basic Editor) (shortcut Alt-F11)
Insert > Module
Paste the code into your new module.
Use:
Select the cells you want to merge.
Tools > Macro > Macros... (shortcut Alt-F8) > select MergeRanges > Run
If you want the macro to work with "special formats" such as dates, then you should change .Value2 to .Text.
in Excel, press Alt-F8
use the dialog to add an empty macro "MergeRanges"
add your code above.
To run the code, select some cells you want to merge, press Alt-F8 again and run that macro.
Highlight some cells you want to merge (not dates or currency) and the press Alt+F8 an select this macro. It should (I didn't test) merge the cell contents into a cell without losing any of the contents that were in each cell.
Make sure to insert that code in the file first by pressing Alt+F11 to open VBE and right click the explorer and choose add module. Then paste this code in. Make sure your macro security is low enough to run it.

Resources