Why does my script start two notepad instances without waiting for the user to close the first notepad? I would like that my script opens one text file, than waits for closing of notepad before it opens the next one.
set service = GetObject ("winmgmts:")
Dim ArchiveList
Dim ExportTool
Dim running
ExportTool = "notepad.exe "
ArchiveList = Array("A.txt","b.txt")
For Each element In ArchiveList
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run(ExportTool & element)
running = true
WScript.Sleep 3000
Do while running
running = false
for each Process in Service.InstancesOf ("Win32_Process")
If Process.Name = ExportTool then
running = true
End If
next
Loop
MsgBox "Hallo Erdling", VBOKOnly, "Muhaha"
' not running
Next
I do not understand why this is not working.
running is never set to True by your For Each Process loop as the ExportTool value will not be found in the Services List due to the extra space.
Remove the space and add it where you concatenate the ExportTool and element values:
set service = GetObject ("winmgmts:")
Dim ArchiveList
Dim ExportTool
Dim running
ExportTool = "notepad.exe" ' remove trailing space
ArchiveList = Array("A.txt","b.txt")
For Each element In ArchiveList
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run(ExportTool & " " & element) ' add space
running = true
WScript.Sleep 3000
Do while running
running = false
for each Process in Service.InstancesOf ("Win32_Process")
If Process.Name = ExportTool then
running = true
End If
next
Loop
MsgBox "Hallo Erdling", VBOKOnly, "Muhaha"
' not running
Next
Should work now.
Because
ArchiveList = Array("A.txt","b.txt")
creates an array with two elements, so that the loop starting with
For Each element In ArchiveList
will run for element = "A.txt" and element = "B.txt" and
objShell.Run(ExportTool & element)
will .Run Notepad.exe for each text file.
Related
I have some code which reads in a tab delimited file where cell reference B2 matches the reference in the first column in the tab delimited file. This works fine where the text file is small. The below works on a sample file with aa bb and cc as the headers with dummy data.
Option Explicit
Sub TestImport()
Call ImportTextFile(Sheet1.Range("B1"), vbTab, Sheet2.Range("A4"))
End Sub
Public Sub ImportTextFile(strFileName As String, strSeparator As String, rngTgt As Range)
Dim lngTgtRow As Long
Dim lngTgtCol As Long
Dim varTemp As Variant
Dim strWholeLine As String
Dim intPos As Integer
Dim intNextPos As Integer
Dim intTgtColIndex As Integer
Dim wks As Worksheet
Set wks = rngTgt.Parent
intTgtColIndex = rngTgt.Column
lngTgtRow = rngTgt.Row
Open strFileName For Input Access Read As #1
While Not EOF(1)
Line Input #1, strWholeLine
varTemp = Split(strWholeLine, strSeparator)
If CStr(varTemp(0)) = CStr(Range("B2")) Then
wks.Cells(lngTgtRow, intTgtColIndex).Resize(, UBound(varTemp) + 1).Value = varTemp
lngTgtRow = lngTgtRow + 1
End If
Wend
Close #1
Set wks = Nothing
End Sub
I am trying to get the below bit of code to work using ADO as this will run much faster on a text file with a couple of million records however I am getting an error on the '.Open str' part of the code (no value given for one or more required parameters).
It looks like it is to do with how I am defining the string- could you review and see if there is something I am missing...?
Sub QueryTextFile()
t = Timer
Dim cnn As Object
Dim str As String
Set cnn = CreateObject("ADODB.Connection")
cnn.Provider = "Microsoft.Jet.OLEDB.4.0"
cnn.ConnectionString = "Data Source=C:\Users\Davids Laptop\Documents\Other Ad Hoc\Test Files\;Extended Properties=""text;HDR=Yes;FMT=Delimited;"""
cnn.Open
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
str = "SELECT * FROM [test1.txt] WHERE [aa]=" & Chr(34) & Range("B2") & Chr(34)
With rs
.ActiveConnection = cnn
.Open str
Sheet1.Range("A4").CopyFromRecordset rs
.Close
End With
cnn.Close
MsgBox Timer - t
End Sub
I am trying to enumerate the paragraphs selected by the user in (Neo|Libre|Open)Office.
When I use the code below, modified version from here,
Sub CheckForSelection
Dim oDoc as Object
Dim oText
oDoc = ThisComponent
oText = oDoc.Text
if not IsAnythingSelected(oDoc) then
msgbox("No text selected!")
Exit Sub
end if
oSelections = oDoc.getCurrentSelection()
oSel = oSelections.getByIndex(0)
' Info box
'MsgBox oSel.getString(), 64, "Your Selection"
oPE = oSel.Text.createEnumeration()
nPars = 0
Do While oPE.hasMoreElements()
oPar = oPE.nextElement()
REM The returned paragraph will be a paragraph or a text table
If oPar.supportsService("com.sun.star.text.Paragraph") Then
nPars = nPars + 1
ElseIf oPar.supportsService("com.sun.star.text.TextTable") Then
nTables = nTables + 1
end if
Loop
' Info box
MsgBox "You selection has " & nPars & " paragraphs.", 64
end Sub
it finds ALL the paragraphs in the document, not just in the selection. Google has failed me. Any thoughts on how to find individual paragraphs in the selection?
The oSel.Text is a shortcut for oSel.getText() which "Returns the text interface in which the text position is contained." https://www.openoffice.org/api/docs/common/ref/com/sun/star/text/XTextRange.html#getText
So to get a ParagraphEnumeration only from the Selection, you should use oPE = oSel.createEnumeration() instead of oPE = oSel.Text.createEnumeration().
Currently, the folder I'm importing from has 16,000 files and I only need the latest ones. The amount of lines wouldn't be so bad if it didn't break Excel every time it tried to run. The code I'm using imports them all:
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("X:\TMS\TRUCK_OUT")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, "|")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
Check out the following code - I have commented the extra line of code that i have added
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
Dim fileModDate As Date 'PANKAJ - Added the variable
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("C:\Users\pankaj.jaju\Desktop")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
fileModDate = file.DateLastModified 'PANKAJ - Added this to get the last modified date for each file
If fileModDate > #1/20/2014 1:00:00 PM# Then 'PANKAJ - Added this to get the desired file based on modified date
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, "|")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
' Clean up
FileText.Close
Loop
End If
Next
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
In a recent question, vbscript using InStr to find info that varies within a URL, I had asked about finding info in a URL. I later realized I didn't need to find the info in the URL, I just needed to be able to capture the URL from the location box in Internet Explorer and be able to use it to gather data from a web page. Here's what I have so far:
Option Explicit
Dim objIE, objShell, objShellWindows
Dim strIDNum, strURL, strWindow, strURLFound, WShell, i
'=============================================================
'=== Code for capturing URL of current page will go here ===
'=============================================================
strURL = 'URL that is captured by the above coding
strWindow = "Workflow Process"
Set objIE = CreateObject("InternetExplorer.Application")
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
Set WShell = CreateObject("WScript.Shell")
strURLFound = False
'To fix item not found error
For Each objIE in objShellWindows
Next
For i = 0 to objShellWindows.Count - 1
Set objIE = objShellWindows.Item(i)
On Error Resume Next
If InStr(Ucase(objShellWindows.Item(i).LocationURL), Ucase(strURL)) Then
If InStr(Ucase(objShellWindows.Item(i).FullName), "IEXPLORE.EXE") Then
If Err.Number = 0 Then
If InStr(objShellWindows.Item(i).document.title, (strWindow)) Then
strURLFound = True
Exit For
End If
End If
End If
End If
Next
Once I have the URL for the site my users will be on, I will be using the code below to gather the info:
WShell.AppActivate strWindow
WScript.Sleep 300
strIDNum = objIE.document.getElementByID("ID_PlaceHolder").value
How do I go about getting the URL from the page they are on?
Have you tried objIE.LocationURL? Also, thanks to Tomalak for providing objIE.document.location.href.
I was able to figure out how to get information from another web site with a URL that changes. First, I needed the base URL to at least get me there, once found, it really didn't matter what additional info was in the URL because each page is set up the same, just different data flowing through it. The end result is the code below.
Option Explicit
Dim objIE, objShell, objShellWindows
Dim strIDNum, strURL, strWindow, strURLFound, WShell, i
strURL = "http://www.myworkplace.com"
strWindow = "Workflow Process"
Set objIE = CreateObject("InternetExplorer.Application")
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
Set WShell = CreateObject("WScript.Shell")
strURLFound = False
'To fix item not found error
For Each objIE in objShellWindows
Next
For i = 0 to objShellWindows.Count - 1
Set objIE = objShellWindows.Item(i)
On Error Resume Next
If InStr(Ucase(objShellWindows.Item(i).LocationURL), Ucase(strURL)) Then
If InStr(Ucase(objShellWindows.Item(i).FullName), "IEXPLORE.EXE") Then
If Err.Number = 0 Then
If InStr(objShellWindows.Item(i).document.title, (strWindow)) Then
strURLFound = True
Exit For
End If
End If
End If
End If
Next
WShell.AppActivate strWindow
WScript.Sleep 300
strIDNum = objIE.document.getElementByID("ID_PlaceHolder").innertext
As you can see in the last line, I also used innertext rather than value to get the ID number.
first of all, I am new to the world of scripting. I did a VBScript that adds TCP/IP printers (in a network) to a computer. So far I also managed to change the printers to perform duplex printing with a batch file. Now I need someway to change the printer color settings to print in black & white.
I'd appreciate if you could help me please,
Thanks in advance.
Code to add tcp/ip printer to computer:
strComputer = "."
Dim objWMI:Set objWMI = GetObject("winmgmts://" & strComputer & "\root\cimv2")
Set colItems = objWMI.ExecQuery("Select * from Win32_OperatingSystem", , 48)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
objWMIService.Security_.Privileges.AddAsString "SeLoadDriverPrivilege", True
Install "167.221.10.249" ''printer IP to be added
sub Install(strIP)
InstallPrinterPort strIP
end Sub
strBasePrinter = "PRINTERNAME"
strPrinterName = "Xerox WorkCentre 7120 PCL6" '' Printer controller
strINFPath = "\\167.221.1.67\printer_7120\x2GCHAX.inf" ''path to .inf file
strIPPort = "IP_" & "167.221.10.249"
Set objShell = CreateObject("WScript.Shell")
strCommand = "cmd /c rundll32 printui.dll,PrintUIEntry /if /b """ & strBasePrinter & """ /f " & strINFPath & " /r """ & strIPPort & """ /m """ & strPrinterName & """ & /Z"
objShell.Run strCommand, 1, True
Sub InstallPrinterPort(strIP)
Set colInstalledPorts = objWMIService.ExecQuery _
("Select Name from Win32_TCPIPPrinterPort")
For each objPort in colInstalledPorts
If objPort.Name="IP_" & strIP then exit sub
Next
Set objNewPort = objWMIService.Get _
("Win32_TCPIPPrinterPort").SpawnInstance_
objNewPort.Name = "IP_" & strIP
objNewPort.Protocol = 1
objNewPort.HostAddress = strIP
objNewPort.PortNumber = "9100"
objNewPort.SNMPEnabled = True
objNewPort.Put_
end Sub
During my research i found this. I believe it sets the printer to it's default colors.
Option Explicit
Dim objPrinter
Set objPrinter = CreateObject("WScript.Network")
objPrinter.SetDefaultPrinter "\\ServerName\PrinterName"
' End of example VBScript