Search code examples
vbscripthp-uft

Use VBscript to paste data into a txt file and save


I need to paste data from clipboard (Ctrl+V) into a text file and save it.

I already did some research and it seems that a text file doesn't have a method like SaveAs.

With code below, I could create a new text file and paste data into it, but I can't Save it:

Set WShshell = CreateObject("WScript.Shell")
WShshell.run "c:\WINDOWS\system32\notepad.exe",1
WshShell.AppActivate "notepad"
WShshell.SendKeys "^V" 

I understand there is a method called CreateTextFile, but seems I can't perform paste with it.

I also tried to combine those two:

Set WShshell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile "c:\1.txt",true
WshShell.AppActivate "notepad"
WShshell.SendKeys "^V"

But nothing happened...


Solution

  • UFT has its own clipboard access methods you could use. Here I've created an instance of the clipboard, and extracted its content into sText, then created a text file in C:\temp and written the data from the clipboard directly into it. oFile.Close closes the file and saves it at the same time.

    Dim oClipboard : Set oClipboard = CreateObject("Mercury.Clipboard") 
    sText = oClipboard.GetText ' gets the current content of the clipboard
    
    Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
    Dim oFile : Set oFile = oFso.CreateTextFile("C:\temp\myTextFile.Txt", True)
    
    oFile.Write sText
    oFile.Close