I'm using the following function in my VBScript to copy a string onto the clipboard without the use of the external clip
command (which isn't and cannot be installed due to security policies):
Function CopyToClipboard(sText)
Dim oWord : Set oWord = CreateObject("Word.Application")
With oWord
.Visible = False
.Documents.Add
.Selection.TypeText sText
.Selection.WholeStory
.Selection.Copy
.Quit False
End With
Set oWord = Nothing
End Function
The problem is that the string being copied comes with the standard formatting inherited by the "normal.dot" template.
Given that I have Word 2003, this formatting is Times New Roman, 12pt and in black. So when it gets pasted into an email or document, the formatting doesn't match with the existing content.
Is there any way to remove the formatting on the string in the clipboard?
After playing around a bit, I developed a solution that doesn't use the Word object model, but does copy unformatted text to the clipboard - which is what I needed to do:
Function CopyToClipboard(sText)
' Create temporary text file to avoid IE clipboard warnings
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim sTemp : sTemp = fso.GetSpecialFolder(2) & "\" & fso.GetTempName
Dim oFile : Set oFile = fso.CreateTextFile(sTemp, True)
oFile.Write "This file can be safely deleted"
oFile.Close
Set oFile = Nothing
' Start Internet Explorer in the local zone
Dim oIE : Set oIE = CreateObject("InternetExplorer.Application")
oIE.Visible = 0
oIE.Navigate2 sTemp
Do
WScript.Sleep 100
Loop Until oIE.Document.ReadyState = "complete"
' Copy contents to clipboard
oIE.Document.ParentWindow.ClipboardData.SetData "text", sText
' Clean up
fso.DeleteFile sTemp
Set oIE = Nothing
Set fso = Nothing
End Function
This code uses Internet Explorer's ability to access the clipboard in order to paste in the contents of sText
. You'll notice that about:blank
isn't used as the starting page and this is because it will generate the following warning:
In order to get around this we create a temporary file locally (with some copy to indicate that it is benign) and then navigate to this file. As a result Internet Explorer treats this page in the "Local Intranet" zone and allows access to the clipboard without generating a pop-up confirmation.