Copying the content of multiple UserForm textboxes to clipboard - vba

I built a Microsoft Word template with a userform containing textboxes. I want to copy the data of two textboxes into the clipboard separately upon submitting the completed userform. Just to clarify I want each textbox to have its own entry into the clipboard for easy access in the future.
Below is the code I'm using but when I repeat the procedure it replaces the first textbox in the clipboard with the second. Any help would be greatly appreciated.
Sub ComandButton_click()
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText Me.TextBox1.value
clipboard.PutInClipboard
End Sub
EDIT (additional background):
For accessing the information put on the Clipboard I created a custom QAT. One of the buttons on the toolbar opens the clipboard so they can easily begin to paste the name they need at any one time. Most reports involve two people so I want to send the value of two textboxes into the clipboard as if you individually selected and copied each name. My first idea was to assign a keyboard shortcut to the value of the two textboxes but I settled on utilizing the clipboard tab.

Given what you've told us, I'm guessing you're calling up the Office Clipboard. This is different from the Windows Clipboard, which is what your code is using. The Office Clipboard is not exposed to the developer (for internal, MS use only). There is a way to put information on it, but I'm uncertain how reliable it is; YMMV (your mileage may vary).
The code for your UserForm to call a procedure responsible for writing the information:
PutContentOnOfficeClipboard Me.[textBoxName].Value
PutContentOnOfficeClipboard Me.[textBoxName].Value
The procedure writes the text to the end of the document, copies it, then deletes again. In my tests, this all shows up on the Office Clipboard:
Sub PutContentOnOfficeClipboard(s As String)
Dim rng As word.Range
Set rng = ActiveDocument.Content
rng.Collapse wdCollapseEnd
rng.Text = s
rng.Copy
rng.Delete
End Sub
If it turns out to be unreliable, then you need a different approach. Here are some thoughts on alternative methods...
A taskpane is optimal as it makes the information visibly available users. Unfortunately, task panes aren't available to the VBA Developer. They can be used from a VSTO solution or an Office-JS solution, but that may be more effort than you're willing/able to put into the project (steep learning curve, enterprise deployment requirement, etc.)
Besides keyboard shortcuts (which aren't a bad idea to have in addition to any visible interface):
A dropdown list on the QAT or the Ribbon
Two buttons on the QAT or the Ribbon
Modify the Right-click (context) menu with two controls to which you can write the names as needed. (Requires call-back macros to make the dynamic update)
Save the entries as AutoText/Building Blocks, possibly to use in conjunction
with a BuildingBlock content control (which can be filtered to show only your entries; AutoText can also be used selectively from the keyboard).
Make a small, non-modal UserForm with buttons. You could optionally use the Windows API to make it "always on-top".

Related

MS Office - ActiveX Buttons switching places

There are several instances of this problem, but this one is predominant. This is in relation to updates (our most notable problem child being KB2726958). We have a Leave Spreadsheet that looks like this:
Leave Spreadsheet example
By pressing the grey Leave button, you end up here:
Leave Word doc
All the programming for these is written in VBA (i've never worked with VBA before, I can understand it to a degree).
Now, the issue is that using the ActiveX button in the 'Leave Spreadsheet example' causes the 2 buttons 'Send by Email' and 'Save' to switch functions; Send by email attempts to save and save opens up Outlook and creates the email message.
Both functions have completely retained functionality, just on the wrong buttons.
The thing I find weird is that a hyperlink to the very same file works; the buttons aren't switched and have full functionality. The only hint that I have towards resolution is that when using a hyperlink, it's directly opening the file. When using the ActiveX button, it seems to be creating a new file based off the file it's linking to. For example, the hyperlink directly opens C:\Report.dotm but the ActiveX button opens Document1.doc with a template based on Report.dotm.
I'm considering that maybe the activeX button is opening up Word with an incorrect extension? But i'm not sure how to figure this out (code below shows that the linked file on the activeX control is a .dotm).
What further throws a spanner into the mix is that it only affects some computers... Considering on-site we all use the same type of PC with the same image... :(
My question is, does anyone know why they may be swapping? They're located on the same network drive albeit different directories. They require the same permissions to access. The code for the buttons is as follows:
Excel Button:
Private Sub CommandButton1_Click()
' This button links the excel spreadsheet to the word doc
Dim wrdApp As Object
Dim wrdDoc As Object
Dim i As Integer
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add("\\networkdrive\directories\Request for Leave.dotm")
End Sub
Word buttons 1 and 2:
Private Sub cmdSend_Click()
' This is the code for the button 'Send by Email'
MsgBox "Send the following email to your Team Leader/Line Manager", vbInformation
SendDocumentAsAttachment "", "IPL Request for Leave"
End Sub
Private Sub cmdSave_Click()
' This is the code for 'Save'
modSend.SaveLeaveForm
End Sub
Please Note: The comments above are not in the code in VBA, i've written them in myself in this question to provide clarity.
Troubleshooting that i've done:
Removing all .exd files
Running the MS Hotfix (removes all .exd files in a GUI)
The next step would be to try running all 6 patches related to fixing ActiveX controls with the particular patches we've done to see if that fixes the problem. The reason I haven't done this yet is because of ITIL (Change management) although I may try testing this later today.
What is the outcome i'm after?
Ideally, I want to understand what is causing these buttons to, from what it looks like, swap their functions. I have different scenarios of button swaps, some of which are remedied by removing the .exd files, and some that aren't.
By understanding what is happening, I hope that I can apply the knowledge to the other scenarios (same problem, different coding).
Then, I'll be able to document my findings so that when we perform the next round of patching that is known to break ActiveX controls, my organization will know how to deal with it.
So the patch mentioned below has fixed this issue. There's still some other issues that I need to test this patch against, but I definitely should have started there. Lesson learnt.
From my work email:
I’ve just tried using the patch related to the ActiveX controls breaking, KB2920754. I’ve used it on two PC’s here in the training room; both had different issues:
- The first one had buttons that had switched around (save attempted to email, email attempted to save)
- The second one couldn’t use the buttons at all.
This patch cured both w/o requiring a restart or logging out and back in. I didn’t remove any .exd files, either.
It does state, however:
“Important For this fix to be fully effective, you also have to apply the other patches for Office 2013 that are listed in the "Resolution" section of the following Microsoft Knowledge Base article”
There are 6 in total.
Patches:
1. KB2920754 – (the one I’ve used successfully)
2. KB2956145
3. KB2956163
4. KB2965206
5. KB2956176
6. KB2956155

Accessing Hyperlink file explorer using VBA

I am creating a spreadsheet to act as a central point of all the documentation relevant to a project, so that all the quotes, drawings etc will all be in a single excel document with hyperlinks to the files along with information about them. (e.g. for a drawing, the drawing name and number will be requested)
I want to do this through a userform in order to ensure sufficient information is supplied as this will be referenced during audits.
But I am having difficulty with the hyperlink part as there may not be a known address/name that allows me to use the hyperlinks.add method.
What would be optimal is the ability to click the Hyperlink button on the ribbon from inside the userform.
This is my first time asking a question, been trawling through stack overflow for a while now though. But I am open to suggestions about asking better questions etc.
Cheers.
Append Hyperlink to list using the Insert Hyperlink Dialog
Private Sub btnInsertHyperlink_Click()
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
Application.Dialogs(xlDialogInsertHyperlink).Show
End Sub

Manipulating objects in design view

I have worked on several projects now where I have been stumped by MS Excel and MS Access where I cannot use VBA to manipulate objects whilst in design view. They are very simple tasks such as changing the name of the labels on a userform in MS Excel or adding new textboxes to a report in MS Access but they seem to be impossible as any macro will only be used upon activation of said userform or report and so everything is just done in runtime.
To focus on one, In MS Excel I want to be able to run a code which will go through all the labels on my userform and rename them from "Label1", "Label2", etc... to "Lbl1", "Lbl2", etc... for instance but I cannot just click a button to run a macro on the design of the userform which would run through all the labels and change their names. If I am able to do this then I can be much more efficent with the rest of my runtime code. Without it, I have the option of renaming every single label I have but there are near 100 labels and I want to do this through VBA as I already can see that it would be very useful to know how to run code in design view of these Visual Basic elements.
Please could you advise whether it is possible to manipulate these VB objects in design view?
You can program the project from code if you set a special macro permission.
Details are on Chip's site: http://www.cpearson.com/excel/vbe.aspx
No, it's not possible. If you have a designer open for Form1 and type Form1.Show in the immediate pane, the VBE will close the designer before it brings up the form. That's just the way it is.
Now, if you have labels Label1, Label2 and Label3, you have what I like to call meaningless identifiers. Renaming them to Lbl1, Lbl2 and Lbl3 will make things even worse.
And if you're referencing them anywhere in code, renaming them will break your code. It's even worse with buttons or anything else with events you're handling: renaming Button1 to Btn1 will not rename the Button1_Click() procedure to Btn1_Click().
Use meaningful names. If Label1 is sitting atop a textbox for, I don't know, some username, then name it lblUserName or UserNameLabel. Use meaningful names. Always.
I've written a refactoring tool for renaming things, that deals with event handlers and many other things; you could right-click a reference to Label1 in your code, select Refactor > Rename from the context menu, enter a new name, and the tool renames all references, and the control itself. The tool in question is called Rubberduck, and does quite a lot more than just letting you rename things, too.
If the labels aren't referenced anywhere in code, then they don't need a name. Why bother?
You can run code from a normal module to alter the design of a userform. You must have trusted access to the VBA Project in your Trust Center settings. Then it's simply a question of using the Designer property of the relevant VBComponent:
Sub foo()
Dim ctl As MSForms.Control
Dim lCounter As Long
lCounter = 1
For Each ctl In ThisWorkbook.VBProject.VBComponents("Userform1").Designer.Controls
If TypeName(ctl) = "Label" Then
ctl.Name = "lbl" & lCounter
lCounter = lCounter + 1
End If
Next ctl
End Sub
The form must not be loaded when you run this.

Word add-in, custom layout

Is it possible to create a custom layout, existing ones are:
Print layout
Full Screen reading
Web layout
Outline
Draft
These can be found in the View Ribbon under the group Document Views.
My aim is to get my own layout button in either the existing View Ribbon (if it is possible to modify it) or add a new layout to my custom Ribbon.
Thanks in advance!
This answer is going to provide information on how to change standard settings of any view type control and associate these changes with certain document. This will not work with all documents and will not change the control action for whole Word Application but for one document. Operation could be repeated for few document and almost all Word button.
Important! I'm not using English version of Office application therefore some description will not match exactly to what you have. Tried and tested for Word 2010.
There are following steps to go:
Open new document- one where control should work according to your private expectations.
Go to View >> Macros >> Show list of macros
In the combo-box below middle of the Macro window choose something like Word application commands (or Word macros or similar). As a result you get list of lots of macros names.
You need to guess which of the macro is associated with ribbon control you are going to change. Use common sense and logic to find it. Sometimes two or three seems to match and possibly you will need to make a try.
A) let's try to change behaviour of draft/pending/working view ribbon control. one rounded red below:
B) find macro ViewNormal (but not ViewDraft)
C) select this macro on the list
Change back on the combo-box list to your document (while keeping your chosen macro selected)
Press Create button on the right in the macro window. You will be moved to VBA Editor to the following code:
Sub ViewNormal()
'
' ViewNormal Makro
' Zmienia widok edycji na normalny
'
If ActiveWindow.View.SplitSpecial = wdPaneNone Then
ActiveWindow.ActivePane.View.Type = wdNormalView
Else
ActiveWindow.View.Type = wdNormalView
End If
End Sub
This code is responsible for working of chosen ribbon control.
First, let's check if we can take control of ribbon button- add MsgBox "Control taken" at the end of the code, before End sub. Back to Word App and press button on the ribbon which result should be- setting of chosen view and our message box.
Now you need to change your code accordingly to set your view as you need. Use VBA for that.
Save document as .Docm and all the changes will be applied to the document each time you press chosen ribbon button.

Accessing Excel Object without using Shape.Activate() on a Word document using VBA

I have a tried reading an embedded excel document in a word document. I followed the code specified at this blog article:
http://vbadud.blogspot.com/2010/08/how-to-read-excel-sheet-embedded-in.html
Dim oWB As Excel.Workbook
Dim oIShape As InlineShape
For Each oIShape In ActiveDocument.InlineShapes
If InStr(1, oIShape.OLEFormat.ProgID, "Excel") Then
oIShape.OLEFormat.Activate
Set oWB = oIShape.OLEFormat.Object
oWB.Sheets(1).Range("A1").Value = "ProdID"
End If
Next oIShape
It works fine but the Activate line causes the document to flicker on each excel document I read. I tried to remove the oIShape.OLEFormat.Activate code but it causes the next line to throw a "Runtime error '430' (class does not support Automation or does not support expect).
The question is there any other way to access embedded excel without calling the Activate method?
This is tricky! The short answer is, no. Not with an embedded Excel.
I did some experimentation and some research. Since I could not find any sources that specifically explained the behavior. this is somewhat a guess on my part. It appears that when you embed the Excel spreadsheet into your word document essentially Word stores a link of spreadsheet, which displays only the appearance because it needs to be interpreted with the Excel program. Until you actually active the shape, you cannot interact with it because that cannot be done with Word directly. This article alludes to the behavior, but doesn't explain it. Here's a quote:
If you edit the object in Word, click anywhere outside the object to return
to the destination file.
If you edit the object in the source program in a separate window,
click Exit on the File menu of the source program to return to the
destination file.
You may have noticed that even if you use. Application.ScreenUpdating = false it still does the flickering you mention. This is because you are using a different application when you access the shapes! Every time you active the shape, the object specific menus etc load.
A possible work around:
If instead of embedding Excel Spreadsheets via the insert menu, you can instead add a control. On my machine using Office 2003 the comparible one is: Microsoft Office Spreadsheet 11.0 This is technically a web control, but the methods and behavior are very comparable to an Excel workbook.
Using the control instead of the handy inserted object, with a slight variation of your code I was able to comment out your activate command and the code ran as expected. Specifically, I had to change these lines:
Dim oWB As Spreadsheet instead of Excel.Workbook.
If InStr(1, oIShape.OLEFormat.ProgID, "OWC11.Spreadsheet.11") Then instead of "Excel"
Basically you can decide... Activate your embedded object that requires Excel to interpret, or use a different control that doesn't require activation.