Access The Nth Item of Clipboard - vba

Is there a way to retrieve several items from the clipboard? I'm using something like this:
Dim clipboard As MSForms.DataObject
Dim str1 As String
Dim str2 As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
str1 = clipboard.GetText(1)
str2 = clipboard.GetText(2)
However, I get an error where I assign a value to my second variable that says the following:
Run-time error '-2147221404 (800040064)':
DataObject:GetText Invalid FORMATETC Structure
Help is much appreciated!

Turns out there are two clipboards: the Windows clipboard and the Office clipboard.
The Office clipboard can hold up to 24 items (all can be the same type), whereas the Windows clipboard can only hold one item of each type.
Copying to the Windows clipboard is as easy as highlighting then
typing Ctrl-C.
Copying to the Office clipboard is as easy as
highlighting then typing Ctrl-CC. The Office clipboard is only active
if there is at least one Office application open and active at the
time.
In VBA, using the MSForms.DataObject only gets you access to the Windows clipboard, so there is only a single text item available. After a variety of searches, I'm not able to find out how to open/control/copy/paste using the Office clipboard from VBA.
Having said all that, there is likely little reason to use any clipboard when writing and running a VBA macro. You can (temporarily) store those values in unused cells on a worksheet, in a public variable, in a public object, or even a private variable (probably with publically accessible properties). All of those methods serve exactly the same purpose as storing data in the clipboard.
In skimming around the interwebz on this topic, I ran across several references to using the clipboard to copy data between different workbooks, or between Office apps like Excel-to-Word. You still don't need the clipboard for this, as VBA can open the remote/external application/workbook/document and copy/paste the data directly.

Related

How to reference a workbook from another excel instance

I believe my problem is rather simple: I have a workbook and I'm using it to get some data from another software (SAP). When I export the data from the software, it automatically opens a .xlsx file, then what I'd need to do is copy some of the data from this file, paste on my original workbook, and then close the file. The section of my code which is giving me an error is this one:
fileName = "temp1.xlsx"
Set wbBasis = Workbooks(fileName)
This happens because the "temp1.xlsx" file that was opened by the SAP software is in another instance of excel, so my code isn't able to find it.
What I need to know is basically this. How to properly reference this "temp1.xlsx" workbook on my original code so that I'm able to edit it, copy stuff from it, close it, etc.
I've found some similar topics to my problem, like the two I'm listing down here, but couldn't adapt the solutions to my situation, and that's why I'm posting this new one.
Having multiple excel instances launched, how can I get the Application Object for all of them?
Finding a workbook in one of multiple Excel instances
Thank you in advance.
You don't need multiple instances of Excel, and you don't need the Excel file to be open in order to get information from it, either with VBA, or even with regular "linked formulas".
For example:
=SUM([C:\yourPath\Filename.xlsx]SheetName!A1:C25)
...returns the sum of cells A1:C25 on a worksheet named Sheetname in an Excel file located at C:\yourPath\Filename.xlsx.
Or you can import all the data directly with Get External Data.
See:
MSDN : Create an external reference (link) to a cell range in another workbook
MSDN : Connect to another workbook
...for more information and examples, search Google for "get data from another Excel workbook".

VBA - excel closes the previous workbook on opening the new one

I have a strange problem, I suscpect it's connected to the version of the Excel, but I'm not sure at all. I can't figure it out alone so I need your help. I have a macro, which operates on a fresh workbook - it's not saved anywhere, as the worker will save it manually afterwards. The macro is a .xlam format add-in, adding a couple of buttons to the ribbon and these buttons start the code.
Inside the code I have simple lines for opening a new workbook, chosen earlier by an user:
Application.DisplayAlerts = False
Set wbMPA = Workbooks.Open(MPA_file)
Application.DisplayAlerts = True
Earlier, the code sets active workbook as an object/workbook the macro will mainly work on (tried both versions):
Set dwb = Application.ActiveWorkbook
and later in the code
dwb.activate
OR:
dwb = ActiveWorkbook.Name
and then
workbooks(dwb).Activate
The lines are in separate subs, but the variable is globally declared.
The code works fine until the opening of wbMPA (watching it in the locals all the time). When I try to open the new file with the code above, the earlier workbook (dwb) just closes itself from unknown reasons.
The error I get from the 1st method is this:
error screenshot
The second one gives a simple "Subscipt out of range".
The errors, however, are not a problem. The problem is the cause of them, which is closing of the workbook from unknown reasons.
It happens only when I open the completely new workbook (using the excel icon on the Start bar) - when I do it from File -> New -> Blank Workbook using already opened workbook, the error does not occur.
Another strange thing - me and my colleague from work use 2013 version of Excel. I never have this error, she has it every time.
This is a general scheme of the code, other things are meaningless in this case because there are no other manipulations of workbooks/worksheets.
Dim dwb As Object
Dim wbMPA As Object
Sub_1()
Set dwb = ActiveWorkbook
Set wbMPA = Workbooks.Open(MPA_file)
Call Sub_2
End Sub
Sub_2()
dwb.Activate
End Sub
I get an error on the activation of dwb in Sub_2, because it closes itself for God knows what the reason on the opening of wbMPA in the Sub_1.
If you have only opened a blank workbook (clicking Excel from Toolbar, for example) and then you open any named workbook before making any changes to the blank workbook, the blank workbook will disappear. I believe that is normal/expected behavior.
I can't speculate why this happens on one computer but not another, but this is always how I have observed new/blank documents (Excel, PowerPoint, Word) to behave, and assume this to be the normal behavior. You may have some different option/configuration on your Excel environment which is changing this default behavior, or maybe you are slightly altering the blank file before running the macro, and your co-worker isn't, etc.
A word of caution to avoid relying on ActiveWorkbook -- and especially in this case if the expectation is to always Set dwb to a new/blank workbook, the best way to do that is to explicitly create a new/blank workbook, rather than relying on the user to manually open a new/blank target workbook.
Set dwb = Workbooks.Add
If, on the other hand dwb must be assigned to some other known/existing workbook, then you should be either providing the file path to an Open statement, or the workbook name to the Workbooks collection.
On a related note, it's almost never necessary to Activate a workbook, see here:
How to avoid using Select in Excel VBA macros
And further note: your variables aren't globally scoped, they're scoped only to the module using Dim statement. A public declaration uses the Public keyword, not the Dim keyword. Both module-scoped and global-scoped should be used with caution (Public moreso than module-scoped) and in most cases it's preferable to pass objects/variables by reference to dependent subs and functions:
How to make Excel VBA variables available to multiple macros?

Secure Excel Workbook (with VBA) from reuse with different data

I have created an Excel Workbook with a lot of VBA code for a customer. The customer will provide me with data. I will import that data into the VBA laden template, Save it as an xlsm, and deliver it to the customer. I get paid by the Workbook so I need to prevent them from trying to copy new data into the existing workbook and reusing it.
How can I somehow prevent the customer from reusing a workbook by just entering in new data on the main Worksheet, then saving as a new Workbook, and getting the use of the VBA code for free. (Alternately they could copy the file in windows then enter new data on the copied version.) I need to detect a significant change in data from the initial imported data.
The data on the main sheet is fairly static (perhaps even totally static on many known columns). I'm thinking about randomly sampling some of the cell data on import (perhaps 10 random cells, or number of rows, etc.), and storing that data somewhere. If, say, 50% of the cells change data, I could just disable (or short-circuit) the public entry points in the code...or something else?
I'd like to allow for some flexibility on the part of the customer, but prevent abuse.
Is there a better way than my general idea, above?
Where could I store that data (it should be part of the sheet, but not changeable by the customer). Perhaps a hidden sheet with password locked cells?
Is there some accepted way of doing this that I'm unaware of?
Perhaps Time-expire the functionality in your code
So thank you for this question. Thank you for setting a bounty. It is a very interesting question given your desire to monetise the VBA code, as a VBA programmer I generally resign myself to not being able to monetise VBA code. It is good that you insist and I will contribute an attempt at an answer.
Firstly, let me join the chorus of answers that say VBA is easily hacked. The password protection can be broken. I would join the chorus of respondents who say you should pick a compiled language as the vessel for your code. Why not try C# or VB.NET housed in a Visual Studio Tools For Office (VSTO) .NET assembly?
VSTO will associate a compiled assembly with a workbook. This mechanism is worth knowing because if you insist on VBA we can use the same mechanism (see later). Each workbook has a CustomDocumentProperties collection where one can set custom properties (it says Document not Spreadsheet because the same can be found in Word so Document is the generalised case).
Excel will look at the workbook's CustomDocumentProperties collection and search for "_AssemblyName" and "_AssemblyLocation"; if _AssemblyName is an asterisk then it knows it needs to load a .NET/VSTO assembly, the _AssemblyLocation provides a lookup to the file to load (you'll have to dig in on this, I forget the details). Reference
Anyway, I'm reminded of VSTO CustomDocumentProperties mechanism because if you insist on using VBA then I suggest storing a value in the CustomDocumentProperties collection that helps you time expire the functionality of your code. Note do not use the BuiltInDocumentProperties("Creation Date") because it is easily identifiable; instead use a codeword, say "BlackHawk". Here is some sample code.
Sub WriteProperty()
ThisWorkbook.BuiltinDocumentProperties("Creation Date") = CDate("13/10/2016 19:15:22")
If IsEmpty(CustomDocumentPropertiesItemOERN(ThisWorkbook, "BlackHawk")) Then
Call ThisWorkbook.CustomDocumentProperties.Add("BlackHawk", False, MsoDocProperties.msoPropertyTypeDate, Now())
End If
End Sub
Function CustomDocumentPropertiesItemOERN(ByVal wb As Excel.Workbook, ByVal vKey As Variant)
On Error Resume Next
CustomDocumentPropertiesItemOERN = wb.CustomDocumentProperties.Item(vKey)
End Function
Sub ReadProperty()
Debug.Print "ThisWorkbook.BuiltinDocumentProperties(""Creation Date""):=" & ThisWorkbook.BuiltinDocumentProperties("Creation Date")
Debug.Print "CustomDocumentPropertiesItemOERN(ThisWorkbook, ""BlackHawk""):=" & CustomDocumentPropertiesItemOERN(ThisWorkbook, "BlackHawk")
End Sub
So you could set CustomDocumentProperty "BlackHawk" to the workbook's initial creation time and then allow the client to use the code for 24 hours, or even 48 hours (careful with weekends, create Friday work through to Tuesday) and then afterwards the code can refuse to operate and instead throw a message saying pay LimaNightHawk more money!
P.S. Good luck with your revenue model.
P.P.S. I read your profile, thanks for your military service.
Whatever you do it will be feasible to crack it (VBA code is easy to crack). However:
there is the contract so... that's not legal for them to do it
you can put part of the code on a FTP server and control physically what is being executed
Very nices ideas here though
Compile Excel file to EXE. Google for that.
Concern 1 seems to be basic re-use of the file. You could create a sub in the ThisWorkbook module to destroy code located in other modules in the event that save-as is selected.
Concern 2 seems to be someone hacking your password protection. A similar tactic could be employed such as using "opening the developer window" as your event instead of save as.
I have experimented with save events to log user entries with great success using the ThisWorkbook module. I am not certain how/if one could detect if the developer tab is opened.
Here's what I've done. Perhaps there is a entirely better approach, or there are tweeks to the below that will make it better:
From the VBA Tools menu > VBAProject Properties > Protection (tab), I Locked the project for viewing with a password.
I created a new "License" sheet.
This sheet is hidden from the user. If you hide the sheet via code like this:
Me.Visible = xlSheetVeryHidden
then then sheet cannot be un-hidden by the user (it requires running vba code to unhide).
On initial import I sample:
Number of imported rows
x number of randomly selected cells *from the columns I know won't/shouldn't change. (There are columns they are allowed to change freely.)
I store these on the "License" sheet in Address / Value pairs.
When the workbook is opened, the Workbook_Open event fires and then does a quick comparison of the current number of rows, and the current values for the addresses stored on the "License" sheet. I then do a percentage calculation: If the rows are more than x% different, or the number of changed values is more that y% then I
Sheets(1).Protect LOCKOUT_PASSWORD
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
There is also a method for unlocking the sheets if necessary.
This might be too simple of an answer, but sometimes we fail to think of the simplest solutions:
Why don't you simply provide the customer with only a copy of the output? You could run their data through your macro-enabled workbook, copy the output sheet into a new workbook, and then break all links so that there's no formulas, updating, or ties to your workbook.
I would create another workbook that contains the code and then reference the customers wb from that one.

copy selection from chrome to excel

I'd like to create a quick way of copying and pasting in between Chrome and Excel. The program would need to perform a task of pasting the selection in a given cell. If we access Excel it's fairly easy, we just need to use Microsoft Forms Library in order to get what we copied to clipboard and paste it in the highlighted field. I'd like to extend this process. Now it looks as follows:
I copy something in Chrome
I need to switch to Excel and access the macro in order to paste what's selected
What I have so far:
Option Explicit
Public Clipboard As New MSForms.DataObject
Sub pasteTable1()
'Tools -> References -> Microsoft Forms 2.0 Object Library
'of you will get a "Compile error: user-defined type not defined"
Dim DataObj As New MSForms.DataObject
Dim S As String
DataObj.GetFromClipboard
S = DataObj.GetText
Debug.Print S 'print code in the Intermediate box in the Macro editor
ActiveSheet.Paste Destination:=Worksheets("Arkusz1").Range("A1")
End Sub
Would it be possible to skip the intermediate step and make Excel paste what's in the clipboard without having to open it? In other words I'd like to have a way of pasting the contents of clipboard automatically once the selection is made.

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

Basically I need to gather a fair few figures from another workbook (Which is found and can be opened by a UserForm, therefore the location and names are variable). I need to use VBA for this as I also need to populate a chart with this data. I would prefer to not have to open the other workbook in order to do it, but if it is far easier then its OK.
The UserForm is done and works fine, and I have the code I need to populate the chart, however I can't get VBA to pull back the data from the other workbook and assign it to the variables that I need it to.
Any ideas on how I can get VBA to do this? It would be greatly appreciated.
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.