excel copy and paste in Windows Search - windows

I am using Excel 2010 and Windows 7 Pro. I want to copy one cell content into Windows Search box. How do I write a VBA for that?
Sub CopytoSearchWindow()
'CopytoSearchWindow Macro ' '
sCell = Range(Application.InputBox(Prompt:="Pick the Cell", Type:=8)).Value

You can use the Shell.Application object to do this in conjunction with sending some key strokes.
Example: (replace my searchString bit with whatever you like)
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub searchExample()
Dim searchCell As Range
Dim shellApp As Object
Dim wshShell As Object
On Error Resume Next 'to catch if user presses cancel
Set searchCell = Application.InputBox(Prompt:="Pick the Cell", Type:=8)
On Error Goto 0
If searchCell Is Nothing Then Exit Sub
Set shellApp = CreateObject("Shell.Application")
Set wshShell = CreateObject("WScript.Shell")
shellApp.FindFiles
Sleep 500
wshShell.SendKeys searchCell.Value & "{enter}"
End Sub
Shell.Application reference: http://msdn.microsoft.com/en-us/library/windows/desktop/bb773938%28v=vs.85%29.aspx
Windows scripting host Shell reference: http://msdn.microsoft.com/en-us/library/aew9yb99%28v=vs.84%29.aspx

Related

CreateTextFile error

I am getting a 'Permission denied' error when trying to run this VBScript after dragging another file or folder icon onto the script's icon.
I have tried running it on two Windows 10 machines and if I run it with arguments if objects at the file creation line, otherwise the scripts completes normally.
Any ideas?
Option Explicit
Dim objFSO
Dim objShell
Dim fldTest
Dim fileTest
Dim strPath
Dim txsOutput
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set txsOutput = objFSO.CreateTextFile("Test.txt")
For Each strPath In WScript.Arguments
fldTest = objFSO.GetFolder(strPath)
For Each fleTest In fldTest.Files
...
Next
Next
txsOutput.Close()
Set txsOutput = Nothing
Set objFSO = Nothing
WScript.Quit

VBA:IE-How to assign pathname to file input tag without popup file upload form?

I am currently doing automaiton for file uploading
Below is HTML tag for input file tag:
<input name="file" title="Type the path of the file or click the Browse button to find the file." id="file" type="file" size="20">
And below is button HTML Tag:
<input name="Attach" title="Attach File (New Window)" class="btn" id="Attach" onclick="javascript:setLastMousePosition(event); window.openPopup('/widg/uploadwaiting.jsp', 'uploadWaiting', 400, 130, 'width=400,height=130,resizable=no,toolbar=no,status=no,scrollbars=no,menubar=no,directories=no,location=no,dependant=no', true);" type="submit" value="Attach File">
My VBA coding is:
Dim filee As Object
Set filee = mydoc.getElementById("file")
filee.Value = filenamepath
Set attach = mydoc.getElementsByName("Attach")
attach(0).Click
When I am running this coding, input filepath box not assign path name so i am getting chose file path.
Find attach screenshot.
Finally i have tried below code but that send key not executing
Dim filee As Object
Set filee = mydoc.getElementById("file")
filee.Click
obj.SetText filename
obj.PutInClipboard
SendKeys "^v"
SendKeys "{ENTER}"
Set attach = mydoc.getElementsByName("Attach")
attach(0).Click
Set finall = mydoc.getElementsByName("cancel")
finall(0).Click
Kindly tell me the windows API program to assign my file name directory in fine name: input box on opened Choose File to Open explorer and click the open button.
I fixed this issue by running external VBScript contain file path to set it on 'Choose File to Upload' pop up window using SendKeys method after send Enter Key to close this pop up, and this run successfully because the extranl VBScript run on another process so it will not stuck on VBA code.
Notes:
1- I dynamically create the external VBScript from VBA code and save it on Temp folder after that I run this script using WScript.Shell.Run to excute it on another thread
1- At the begining of the external VBScript I set 1 sec delay to be sure the 'Choose File to Upload' pop up window already opened from VBA.
And here is the complete code:
....
....
Set filee = mydoc.getElementById("file")
CompleteUploadThread MyFilePath
filee.Foucs
filee.Click
....
....
Private Sub CompleteUploadThread(ByVal fName As String)
Dim strScript As String, sFileName As String, wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
'---Create VBscript String---
strScript = "WScript.Sleep 1000" & vbCrLf & _
"Dim wsh" & vbCrLf & _
"Set wsh = CreateObject(""WScript.Shell"")" & vbCrLf & _
"wsh.SendKeys """ & fName & """" & vbCrLf & _
"wsh.SendKeys ""{ENTER}""" & vbCrLf & _
"Set wsh = Nothing"
'---Save the VBscript String to file---
sFileName = wsh.ExpandEnvironmentStrings("%Temp%") & "\zz_automation.vbs"
Open sFileName For Output As #1
Print #1, strScript
Close #1
'---Execute the VBscript file asynchronously---
wsh.Run """" & sFileName & """"
Set wsh = Nothing
End Sub
As setting the value of a file input element is disabled due to security reasons, the "send keys" method seems to be the only option for automating file uploads using the IE API.
I just stumbled over the same problem that the code after the Click does not seem to be executed - that is, unless the dialog is closed. This indicates that the Click method is blocking, making it impossible to interact with the dialog from within the macro.
I could solve that by using a different method to open the dialog: by setting the focus to the file element with Focus, and sending the space key with SendKeys.
In your case, replace
filee.Click
with
filee.Focus
SendKeys " "
leemes's method(Sending key to the file selection button on IE) is an easy way to automate the file selection procedure.
In addition, if IEObject.Visible sometimes fails to give focus to the IE Window,
we'd better send the IE window to the top-most position using Windows API before using 'SendKeys' like following:
#If VBA7 Then
Declare PtrSafe Function SetForegroundWindow Lib "user32" (ByVal hwnd As LongPtr) As LongPtr
Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Any, ByVal lpWindowName As Any) As LongPtr
#Else
Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Any, ByVal lpWindowName As Any) As Long
#End If
Sub Test()
'first create or get IE object
Set IE= ...
...
'second, send IE window to the foreground
Dim TargetWnd
TargetWnd = FindWindow("IEFrame", vbNullString) 'find IE window
If TargetWnd = 0 Then Debug.Print "Window not found." 'Else Debug.Print TargetWnd
SetForegroundWindow (TargetWnd)
'sendkeys
set filee = getElement....
filee.Focus
SendKeys " " 'send Space key instead of .Click method
SendKeys "filePath" ' "C:\path\filename" ' Type-in the filename
SendKeys "{Enter}" 'closes the file dialog
'finally submit
...
...
end Sub

Opening a user form in Powerpoint via VBScript

I am trying to open a user form which I have created in a PPTM file via VBScript. Code for VB script is as below. This does seem to be working. It is simply opening that macro PPTM and closing it. Any suggestions?
Option Explicit
Dim pptApp, pptPresentation, CurrentDirectory
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = fso.GetAbsolutePathName(".")
Set pptApp = CreateObject("PowerPoint.Application")
Set pptPresentation = pptApp.Presentations.Open(CurrentDirectory + "\Revison Macro V1.pptm",True)
On Error Resume Next
pptApp.Run "Revision"
If Err Then
End If
pptPresentation.Close
pptApp.Quit
Set pptPresentation = Nothing
Set pptApp = Nothing
WScript.Quit
A Few code revisions
Set pptPresentation = pptApp.Presentations.Open(CurrentDirectory + "\Revison Macro V1.pptm",True) >> VBScript uses "&" rather than "+" even though this worked fine, it's better to stick to the correct string handling.
The userform needs to be indirectly called to pause the vbscript. So create a separate Sub and call it "Call_Revision". The code will be simple and straightforward as follows:
Sub Call_Revision
Revision.Show
End Sub
When you execute the .Run command, it needs to know how to find the code to run the UserForm. So now that we have established our sub, we can use that to show the form.
From: pptApp.Run "Revision"
To: pptApp.Run "Revison Macro V1.pptm!Module1.Call_Revision"
If you are waiting for the user to close out the userform to execute the rest of the code and exit the PPTM file, you can apply the following OnClose event within the Userform:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Application.Quit
End Sub
And the Full Code:
Option Explicit
Dim currppt : currppt = "Revison Macro V1.pptm"
Dim ModuleName: ModuleName = "Module1"
Dim OpenUF : OpenUF = "Call_Revision"
Dim pptApp, pptPresentation, CurrentDirectory
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
CurrentDirectory = fso.GetAbsolutePathName(".")
Set pptApp = CreateObject("PowerPoint.Application")
Set pptPresentation = pptApp.Presentations.Open(CurrentDirectory & "\" & currppt,True)
On Error Resume Next
pptApp.Run currppt & "!" & ModuleName & "." & OpenUF
msgbox "Done"
pptPresentation.Close
pptApp.Quit
Set pptPresentation = Nothing
Set pptApp = Nothing

Open directory chooser dialog in specific dir

I've got the following code to display a directory chooser dialog
Function selectOutputFolder(lastPath As String) As String
Const BIF_NEWDIALOGSTYLE = &H00000040
Dim objShell As Variant
Dim objFolder As Variant
Dim objFolderItem As Variant
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Choose a directory", BIF_NEWDIALOGSTYLE, lastPath)
If Not (objFolder Is Nothing) Then
Set objFolderItem = objFolder.Self
selectOutputFolder = objFolderItem.Path
End If
End Function
I was playing around with the 4th parameter of BrowseForFolder which is only a limit for the directory traversal and not to jump into this folder on open.
This is implemented into a lotus script agent, so if you know any alternative in vba or lotusscript, let me know!
There is a "Standard" way to do this in LotusScript by using the SaveFileDialog- Method of the NotesUIWorkspace- Class.
'...your sub goes around this
Dim ws as New NotesUIWorkspace
Dim varPaths as Variant
varPaths = ws.SaveFileDialog( True , "Choose file" , "" , lastPath )
If not isEmpty( varPaths ) then
selectOutputFolder = varPaths(0)
End If

Use clipboard from VBScript

I am looking for a method to place some text onto the clipboard with VBScript. The VBScript in question will be deployed as part of our login script. I would like to avoid using anything that isn't available on a clean Windows XP system.
Edit:
In answer to the questions about what this is for.
We wanted to encourage users inside our organization to use the file server to transfer documents instead of constantly sending attachments by email. One of the biggest barriers to this is that it isn't always obvious to people what the correct network path is to a file/folder. We developed a quick script, and attached it to the Windows context menu so that a user can right click on any file/folder, and get a URL that they can email to someone within our organization.
I want the URL displayed in the dialog box to also be placed onto the clipboard.
GetNetworkPath
Another solution I have found that isn't perfect in my opinion, but doesn't have the annoying security warnings is to use clip.exe from a w2k3 server.
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo hello world | clip", 0, TRUE
Example with a multiline string as per question below :
Link1
Dim string
String = "text here" &chr(13)& "more text here"
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo " & String & " | clip", 0, TRUE
Using Microsoft's clip.exe is the closest to having a clean Windows XP system solution. However you don't have to call CMD.EXE to host it in order to use it. You can call it directly and write to its input stream in your script code. Once you close the input stream clip.exe will write the contents straight to the clipboard.
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("clip")
Set oIn = oExec.stdIn
oIn.WriteLine "Something One"
oIn.WriteLine "Something Two"
oIn.WriteLine "Something Three"
oIn.Close
If you need to wait for clip to be finished before your script can continue processing then add
' loop until we're finished working.
Do While oExec.Status = 0
WScript.Sleep 100
Loop
And don't forget to release your objects
Set oIn = Nothing
Set oExec = Nothing
The closest solution I have found so far is a method to use IE to get and set stuff on the clipboard. The problem with this solution is the user gets security warnings. I am tempted to move 'about:blank' to the local computer security zone so I don't get the warnings, but I am not sure what the security implications of that would be.
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate("about:blank")
objIE.document.parentwindow.clipboardData.SetData "text", "Hello This Is A Test"
objIE.Quit
http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1215.mspx
No security warnings, full let and get access:
'create a clipboard thing
Dim ClipBoard
Set Clipboard = New cClipBoard
ClipBoard.Clear
ClipBoard.Data = "Test"
Class cClipBoard
Private objHTML
Private Sub Class_Initialize
Set objHTML = CreateObject("htmlfile")
End Sub
Public Sub Clear()
objHTML.ParentWindow.ClipboardData.ClearData()
End Sub
Public Property Let Data(Value)
objHTML.ParentWindow.ClipboardData.SetData "Text" , Value
End Property
Public Property Get Data()
Data = objHTML.ParentWindow.ClipboardData.GetData("Text")
End Property
Private Sub Class_Terminate
Set objHTML = Nothing
End Sub
End Class
Example Usage.
' Create scripting object
Dim WShell, lRunUninstall
Set WShell = CreateObject("WScript.Shell")
WShell.sendkeys "^c"
WScript.Sleep 250
bWindowFound = WShell.AppActivate("Microsoft Excel")
WShell.sendkeys ClipBoard.Data
To avoid the security warnings associated with Internet Explorer and clipboard access, I would recommend you use the Word application object and its methods to put your data onto the clipboard. Of course you can only use this on a machine that has MS Word installed, but these days that's most of them. (*In spite of the fact that you asked for stuff on a 'clean' system :) *)
' Set what you want to put in the clipboard '
strMessage = "Imagine that, it works!"
' Declare an object for the word application '
Set objWord = CreateObject("Word.Application")
' Using the object '
With objWord
.Visible = False ' Don't show word '
.Documents.Add ' Create a document '
.Selection.TypeText strMessage ' Put text into it '
.Selection.WholeStory ' Select everything in the doc '
.Selection.Copy ' Copy contents to clipboard '
.Quit False ' Close Word, don't save '
End With
You can find detail on the MS Word application object and its methods here: http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx
Microsoft doesn't give a way for VBScript to directly access the clipboard. If you do a search for 'clipboard'on this site you'll see:
Although Visual Basic for Applications supports the Screen, Printer, App, Debug, Err, and Clipboard objects, VBScript supports only the Err object. Therefore, VBScript does not allow you to access such useful objects as the mouse pointer or the clipboard. You can, however, use the Err object to provide runtime error handling for your applications.
So using notepad indirectly is probably about the best you'll be able to do with just VBScript.
Here's another version of using the "clip" command, which avoids adding a carriage return, line feed to the end of the string:
strA= "some character string"
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /C echo . | set /p x=" & strA & "| c:\clip.exe", 2
s = "String: """ & strA & """ is on the clipboard."
Wscript.Echo s
I've only tested this in XP. clip.exe was downloaded from Link and placed in C:\.
I've found a way to copy multi line information to clipboard by vbscript/cmd.
Sequence:
with VBS generate the final "formatted string" that you need copy to clipboard
generate a (txt) file with the "formatted string"
use type command from cmd to paste information to clip by pipe
Example script:
Function CopyToClipboard( sInputString )
Dim oShell: Set oShell = CreateObject("WScript.Shell")
Dim sTempFolder: sTempFolder = oShell.ExpandEnvironmentStrings("%TEMP%")
Dim sFullFilePath: sFullFilePath = sTempFolder & "\" & "temp_file.txt"
Const iForWriting = 2, bCreateFile = True
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
With oFSO.OpenTextFile(sFullFilePath, iForWriting, bCreateFile)
.Write sInputString
.Close
End With
Const iHideWindow = 0, bWaitOnReturnTrue = True
Dim sCommand: sCommand = "CMD /C TYPE " & sFullFilePath & "|CLIP"
oShell.Run sCommand, iHideWindow, bWaitOnReturnTrue
Set oShell = Nothing
Set oFSO = Nothing
End Function
Sub Main
Call CopyToClipboard( "Text1" & vbNewLine & "Text2" )
End Sub
Call Main
The easiest way is to use built-in mshta.exe functionality:
sText = "Text Content"
CreateObject("WScript.Shell").Run "mshta.exe ""javascript:clipboardData.setData('text','" & Replace(Replace(sText, "\", "\\"), "'", "\'") & "');close();""", 0, True
To put to clipboard a string containing double quote char ", use the below code:
sText = "Text Content and double quote "" char"
CreateObject("WScript.Shell").Run "mshta.exe ""javascript:clipboardData.setData('text','" & Replace(Replace(Replace(sText, "\", "\\"), """", """"""), "'", "\'") & "'.replace('""""',String.fromCharCode(34)));close();""", 0, True
Take a look at this post. It describes a hacky approach to read from the clipboard, but I imagine it could be adapted to also write to the clipboard as well, such as changing the Ctrl+V to Ctrl+A then Ctrl+C.
I devised another way to use IE and yet avoid security warnings...
By the way.. this function is in JavaScript.. but u can easily convert it to VBScript..
function CopyText(sTxt) {
var oIe = WScript.CreateObject('InternetExplorer.Application');
oIe.silent = true;
oIe.Navigate('about:blank');
while(oIe.ReadyState!=4) WScript.Sleep(20);
while(oIe.document.readyState!='complete') WSript.Sleep(20);
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>";
var oTb = oIe.document.getElementById('txtArea');
oTb.value = sTxt;
oTb.select();
oTb = null;
oIe.ExecWB(12,0);
oIe.Quit();
oIe = null;
}
Here is Srikanth's method translated into vbs
function SetClipBoard(sTxt)
Set oIe = WScript.CreateObject("InternetExplorer.Application")
oIe.silent = true
oIe.Navigate("about:blank")
do while oIe.ReadyState <> 4
WScript.Sleep 20
loop
do while oIe.document.readyState <> "complete"
WScript.Sleep 20
loop
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>"
set oTb = oIe.document.getElementById("txtArea")
oTb.value = sTxt
oTb.select
set oTb = nothing
oIe.ExecWB 12,0
oIe.Quit
Set oIe = nothing
End function
function GetClipBoard()
set oIe = WScript.CreateObject("InternetExplorer.Application")
oIe.silent = true
oIe.Navigate("about:blank")
do while oIe.ReadyState <> 4
WScript.Sleep 20
loop
do while oIe.document.readyState <> "complete"
WScript.Sleep 20
loop
oIe.document.body.innerHTML = "<textarea id=txtArea wrap=off></textarea>"
set oTb = oIe.document.getElementById("txtArea")
oTb.focus
oIe.ExecWB 13,0
GetClipBoard = oTb.value
oTb.select
set oTb = nothing
oIe.Quit
Set oIe = nothing
End function
In your Class ClipBoard, neither the Clear sub nor the Let Data sub work. I mean they have no effect on Windows Clipboard. Actually, and ironically so, the only sub that works is the one you have not included in your example, that is Get Data! (I have tested this code quite a few times.)
However, it's not your fault. I have tried to copy data to clipboard with ClipboardData.SetData and it's impossible. At least not by creating an "htmlfile" object. Maybe it works by creating an instance of "InternetExplorer.Application" as I have seen in a few cases, but I have not tried it. I hate creating application instances for such simple tasks!
Alkis
If it's just text can't you simply create a text file and read in the contents when you need it?
Another alternative and clearly a kludge, would be to use the SendKeys() method.
No security warnings and no carriage return at the end of line
' value to put in Clipboard
mavaleur = "YEAH"
' current Dir
path = WScript.ScriptFullName
GetPath = Left(path, InStrRev(path, "\"))
' Put the value in a file
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile=GetPath & "fichier.valeur"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write mavaleur
objFile.Close
' Put the file in the Clipboard
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c clip < " & outFile, 0, TRUE
' Erase the file
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile outFile

Resources