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

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

Related

Excel VBA / SAP GUI: how to get Value from Cell in SAP to Excel. "Node?"

I have created an Excel VBA Macro to connect to SAP GUI, pull data, etc. Nearly everything works, but I have one problem.
I am using the Transaction CV04N to download some documents from it. My code pastes all required Document names (or numbers) into the multiple selection here:
After executing it, we get this list:
Now my code just double clicks the list one-by-one and this opens up:
So, in most cases, there is only one PDF file in here, but sometimes there is also a TIFF file in there, which then produces an error, because the program tries to download it as a .pdf.
However I only want the PDF. But my program always just selects the first entry.
So I need a function/routine that reads what is in the first line, if it is not PDF, then take the next one. (there are never 2 PDFs in there, so taking the first PDF that shows up is sufficient)
If I just choose document, that only contain PDFs, then everything runs normal.
My current code looks like this (starts from the window shown in last picture)
For j = 0 To k - 1
On Error Resume Next
FileName = XYZ
SaveName = DlFolder & FileName
Session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").currentCellRow = j
Session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").doubleClickCurrentCell
Set Tree = Session.findById("wnd[0]/usr/tabsTAB_MAIN/tabpTSMAIN/ssubSCR_MAIN:SAPLCV110:0102/cntlCTL_FILES1/shellcont/shell/shellcont[1]/shell")
Tree.selectNode " 1"
Tree.nodeContextMenu " 1"
Tree.selectContextMenuItem "CF_EXP_COPY"
'It has selected the "copy to" in context menu, now just saves it to Folder saved in "Savename"
Session.findById("wnd[1]/usr/ctxtDRAW-FILEP").Text = SaveName
Session.findById("wnd[1]/tbar[0]/btn[0]").press
'goes to next doc:
Session.findById("wnd[0]/tbar[0]/btn[3]").press
Next
So, if I could get the data from the Table, I could select the one with TIFF, for that I need to read the table.
I have tried
Tree.Text
Tree.Value
Tree.Copy (and then paste in Excel)
But nothing gives me the correct value...
When I select the entry, and press CTRL-C and paste it somewhere it gives me the whole line, so a String with all columns in this entry.
If you have a solution just to get that mentioned String into a Excel Cell, that's fine with me! From there I can set up some routine to make it work.
I hope I made it understandable what I want, if not please feel free to reach out to me!

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

Excel macro to simply type predefined text into the active cell, as plain text

Very rudimentary: I wish to press F1 (Windows OS) to print, i.e., "XZ" in the active Excel cell (as plain/unformatted text), but in such a way that I can then enter "123" immediately thereafter, hence resulting in a cell value of XZ123.
This .xls is shared by other users, four of whom are in the document adding data at any given time. We save this to a Sharepoint folder, but nobody on the team ever accesses the document via the web version of Excel. We instead just double-click the document, at which point Excel boots up from our local hard drive, but when the document loads, we can see other users' active cell(s) based on highlights around the cells with their initials.
My hope is that this silly two-letter automation can be triggered only from my computer, and not embedded in the document file itself.
Huge thanks in advance for any guidance! This seems crazy simple but I honestly can't figure out how to do it. Cheers!
Unfortunately the only way for vba to enter edit mode is to use SendKeys
You'll need to use OnKey to map the function to F1
Const StringToEnter As String = "XZ"
Sub EnterValue()
Application.SendKeys "{F2}" & StringToEnter
End Sub
' Run this once to map F1 key. Maybe call from the `Workbook_Open` event
Sub SetupMappingToF1()
Application.OnKey "{F1}", "EnterValue"
End Sub

Opening a tiff file from Excel causing loss of Cell Edit functionality

I have a spreadsheet, with different people using copies on different PC's. There is a macro triggered by Worksheet_Selection_Change that opens an image file. On two of the PC's, when the workbook is opened, the user can't edit a cell without double clicking in it. Also, the Selection_Change event is not triggered unless double clicked. In the options, "Allow Editing Directly in Cells" is checked. On my PC, this works fine, meaning I can edit cells.
We tried all the workarounds offered here:
https://social.technet.microsoft.com/Forums/ie/en-US/b3f38d61-698a-4117-84a7-e73e3e209c25/excel-2013-unable-to-type-in-cell?forum=officeitpro
and here:
https://www.mrexcel.com/forum/excel-questions/345218-cannot-enter-text-cell-unless-double-click.html
Some of these work, until an image was opened, then it was back to not allowing editing, and we had to restart the workbook.
It could be that something in the macro was causing this to happen, except I then erased all the code, made a hyperlink to the images (all the macro did was open images), and similar behavior would occur. You could edit cells, until you opened an image (using the hyperlink this time), and then you could not edit cells.
Furthermore, like I said on my computer this does not happen at all, and when we checked, same exact version of Windows, same exact version of Excel (14.0.7190.5000).
Is this just a random bug in Excel?
Am I missing something obvious?
It makes 0 sense to me why this would be happening on some PC's and not others.
Does anyone know how I can solve this?
Here is what I want to occur: User opens a spreadsheet. They can edit cells directly. User either:
A) Clicks a hyperlink directed to an image file which then opens on her computer.
or
B) Clicks a cell in the spreadsheet, which triggers the following code to run:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count = 1 Then
If Target.Column = 1 Then
Dim Shex As Object
Dim tgtFile As String
Dim fileName As String
fileName = Cells(Target.Row, Target.Column).Value & ".tif"
Set Shex = CreateObject("Shell.Application")
tgtFile = ThisWorkbook.Path & "\" & fileName
Shex.Open (tgtFile)
End If
End If
End Sub
Then after either A or B is completed, and the user has opened the image file, she can go back to the spreadsheet, and can still edit cells directly.
What is actually happening is the user is completing A or B, and then going back to the spreadsheet, and now all of a sudden can not edit cells directly. This only happens on some computers, not others, and all computers are on the same version of Windows and Excel.
Also, a copy of the spreadsheet can be found here:
http://batesplus.com/temp/example.xlsm
How do I make it so that a user can open an image, and then go back to the spreadsheet, and still be able to edit cells?
Thank you

copy text from one excel to another one

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.

Resources