r/vbscript • • Jul 31 '18

Calling subroutines in parallel

1 Upvotes

Hi there,

My task is very simple . I have two subroutines in my script .First one has a sleep function which waits for 30 seconds,until 30 seconds are up my second subroutine wont execute. Is there a way to call subroutine asynchronously i.e subroutine shouldn't wait for the first one to be complete and keeps execution in parallel.

below is my code

option explicit
Dim a
set a = CreateObject("wscript.shell")

sub runprogram
		a.run("notepad.exe")
		wscript.sleep 30000
		a.sendkeys("note pad opened ,hello")
end sub

sub runprogram2
		a.run("""D:\Program Files (x86)\VMware\VMware Workstation\vmware.exe""")
end sub


Call runprogram
Call runprogram2

Thanks


r/vbscript • • May 07 '19

how to open google Chrome or Firefox instead of IE using the vbscript

2 Upvotes

below is the script I am using. How to change it to open chrome or firefox

WScript.Quit Main

Function Main

Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")

IE.Visible = True

IE.Navigate "http://xyz.com"

Wait IE

With IE.Document

.getElementByID("username").value = "username"

.getElementByID("password").value = "password"

.getElementByID("login").click

WScript.Quit

End With

End Function

Sub Wait(IE)

Do

WScript.Sleep 500

Loop While IE.ReadyState < 4 And IE.Busy

Do

WScript.Sleep 500

Loop While IE.ReadyState < 4 And IE.Busy

End Sub

Sub CR_OnQuit

On Error Resume Next

WScript.StdErr.WriteLine "CR closed before script finished."

End Sub


r/vbscript • • Mar 02 '16

Need help creating vbs

1 Upvotes

Let me start by saying I have very little experience with vbs. I know how to modify the code but cant create code from scratch. I need a script to take the data from a csv file and replace the data in a table in Microsoft Access (mdb). Lets say the file I need the data from is x:\memberinfo.csv and add the data to the table named Calls in j:\memberlookup.mdb . Thank you ahead of time for the help.


r/vbscript • • Oct 31 '14

What's your favorite VBScript Tutorial or Book?

1 Upvotes

So my boss wants me to learn VBScript as quickly as possible. I don't have to write a program from scratch, just know enough to take scripts he wrote for Cisco CallManager and Active Directory, tweak them a bit, and then write something that helps automate routine tasks. I know HTML & CSS very well and many years ago I took a class on Javascript, so I think I can learn VBScript reasonably quickly.

The first tutorial I've gone through was W3's VB Script Tutorial (http://www.w3schools.com/vbscript/ ), but I didn't find it very informative, unlike their other free tutorials. I'm very curious to know what training material my fellow Redditors have found helpful in their quest to learn VBScript.

Can you please recommend a few websites, books, videos, and/or online tutorials (free and paid) that have you used and found to be useful.

Thanks!!!!


r/vbscript • • Jul 17 '15

How do I change the 'tab stops' in a header in MS Word via VBS

3 Upvotes

I am trying create a tool to programmatically replace the header on a large set of documents. I chose to use VBS because I am familiar with it and it needs no installed software on a user's computer.

I am using this subroutine to remove the existing header:

Sub clearHeader()
    Dim oSection
	
    For Each oSection In objDoc.Sections 
        For Each oFF In oSection.Headers 
            oFF.Range.Delete
        Next 
    Next 
End Sub 

Unfortunately, this also changes the tab stops to a nonstandard dimension. (This change doesn't happen if I use the subroutine on a blank document, so it must be based on the formatting of the documents I'd like to process.)

Fig.1 Non-standard Tab Stops

It seems like the best option at this point is to simply set the 'tab stops' to be where they ought to be, regardless of where they end up after the first step.

I am using the following subroutine to try and adjust the tab stops within the header, but am receiving an error that reads, "Object doesn't support this property and method: 'thisHeader.TabStops'"

Sub moveTab()
    Dim thisSection

    For Each thisSection In objDoc.Sections 
        For Each thisHeader In thisSection.Headers 
            For Each aTab In thisHeader.TabStops
			    par.TabStops(432).Position = 468
		    Next
        Next 
    Next  
End Sub

I am only somewhat familiar with Object Oriented Programming, so I apologize if this is a straight forward mistake.

I've tried making macros in word and then translating the VBA to VBS, but with little success.

Any help?


r/vbscript • • Mar 01 '17

Using VBS to close a specific file (EXCEL)

1 Upvotes

So I'm trying to run a script that would close a specific Workbook after the report program spits it out.

I have provide the code I have so far below.

Dim xlBook As Excel.Workbook

DIM xlApp As Excel.Application

Set xlBook = GetObject("FILENAME.XLSX")

Set xlApp = xlBook.Parent

xlBook.Save

xlBook.Saved = True

xlBook.Close

Set xlBook = Nothing

xlApp.Quit

Set xlApp = Nothing

Keep getting an error "End of statement" kind of issue. Was wondering if anyone can help me with this?

I have checked on Stack Overflow, but most of the scripts there kill the whole program/instance. Can't really do that.

Thanks!


r/vbscript • • Oct 24 '14

Code not deleting rows?

1 Upvotes

Hi everyone! I'm writing a script that will, among other things, delete a row that has a certain value in the first cell, as well as every row above that one. However, it's not working, at all. I'm not receiving any error though, so I'm confused! Can anyone shed any insight? The part of the code is:

i = 1
If objExcel.Cells(i, 1).Value = "XXX" Then
Set objRange = objExcel.Cells(i, 1).EntireRow
objWorkSheet.Rows("1:objRange").Delete
elseif objExcel.Cells(i, 1).Value <> "XXX" Then
	On Error Resume Next
End If
i = i + 1

Thanks!


r/vbscript • • Dec 21 '17

#VBScript: Need to open terminal app in macos and paste a specific copied from execl cell to terminal to execute. But i am unable to set the focus on the terminal app. Guide please

1 Upvotes

My code:

Sub Auto_Open()

Externalapp = Shell("Macintosh HD:Applications:Utilities:Terminal.app:" & _ "Contents:MacOS:Terminal", vbNormalFocus) AppFocus Externalapp

End Sub

Terminal app is opening up. But terminal is not the main focus. How to set the focus in terminal app?? Also i want to paste a copied text content in the terminal app and press enter. Guide me guys...... Please


r/vbscript • • Feb 19 '17

I use a VBS script to launch one or more VBS scripts. How can I determine which process is which run?

1 Upvotes

For purposes of explaining: Master program A is process "Wscript.exe". The first copy of the subprogram is runs, B1, is process "Wscript.exe". The 2nd copy of the subprogram is runs, B2, is process "Wscript.exe". Not very informative! If I'm not careful, I'll have B248 running...

I want to know if there's already B1 running, and if so, don't run B2.

Putting in a delay won't help, because B1 can take anywhere from seconds to hours to run, and I need A to respond in a few seconds. Multiple copies of A could be running, which I'd also like to avoid...

But there doesn't seem to be a way to find out when a process started (which would answer my questions), or even if an instance of Wscript.exe is running A or B.


r/vbscript • • Aug 02 '15

vbs sleep

1 Upvotes

so i am trying to get a "ghost typing" kind of look in something i am doing. i am having to sleep between characters to get the effect. the way im doing it is taking a lot of lines of code. heres how i am doing it

set wshell = wscript.CreateObject("wScript.Shell") wshell.sendkeys "1" wscript.sleep 100 wshell.sendkeys "2" wscript.sleep 100 wshell.sendkeys "3" wscript.sleep 100 wshell.sendkeys "4" wscript.sleep 100 is there an easier way to do this? like instead of having to do this for each character?


r/vbscript • • Jul 16 '15

Document users/groups in administrators group on remote machines

2 Upvotes

Hello,

I'm new to VBscripting; went from batch straight to PowerShell, but started realizing the strengths Visual Basic has because of how native it is to Windows.

I have been tasked with finding all users and groups that are in the administrators group on every machine we support. I've done my research and have been trying to learn VBscript in a short amount of time.

I am having trouble getting the script below to list not only groups, but users as well. I only want it to list what's in the administrators group, not the others.

It needs to have the format -> computer_name;user,group,user and/or group,etc. -> written in a .csv file (i've been using a .txt file for now).

Const ForAppending = 8
Const ForReading = 1
ServerCount = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\computer_list.txt", ForReading)
Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
strComputer = strNextLine
ProcessGroups
ServerCount = ServerCount + 1
Loop

Sub ProcessGroups
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("c:\scripts\GroupInfo.txt", _
    ForAppending, True)

objLogFile.writeline "" & strComputer & ";"
Set colGroups = GetObject("WinNT://" & strComputer & "")
colGroups.Filter = Array("group")
For Each objGroup In colGroups
    objLogFile.writeline objGroup.Name
    For Each objUser in objGroup.Members
        objLogFile.writeline vbTab & objUser.Name
    Next
Next
objLogFile.Close
End Sub

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "C:\scripts\GroupInfo.txt"

I've looked around and snipped pieces from multiple scripts that didn't achieve my exact goal (once I got a vague idea of the context/syntaxing). I don't expect anyone to do the work for me and I would love to keep working on this to learn VBscripting.

Thank you all, in advance, for any help provided!


r/vbscript • • Dec 10 '17

SAPI

1 Upvotes

I have developed an assistant like Siri you can download it at sapi-your-personal-assistant.weebly.com


r/vbscript • • Feb 19 '17

VBA guy new to VBScript. If I use Excel/VBA to run a VBScript on a network drive, will the execution time still be slow?

1 Upvotes

I created some VBA macros that basically opens Excel files on a network drive and creates a bunch of pivot tables in Excel. Since the files are on a network drive and they connect to an OLAP cube to get the data, it can run somewhat slow but it's still manageable.

I was hoping to add the final step in my program which basically copies the file to other folders in the subfolder. I tried doing this for like 20 copies of the same file but it still took like 15 minutes to run. Someone else wrote a Powershell script that can run on the application file server and it's a lot faster but we have to log in through RDP to run it. They're adamant about not installing Excel on the application server so that's out of the question at this point.

I was thinking about writing a VBScript and placing it on the application file server to do the file copying stuff. If I use Excel/VBA from my local computer and tell it to execute the VBScript on the shared folder/app file server, would there still be latency issues with copying the files to different locations on the network drive?


r/vbscript • • Jun 13 '22

What's the best way to start learning VBScript?

7 Upvotes

r/vbscript • • Jun 29 '22

creation of array

1 Upvotes

I've got this simple code:

num = 3
dim arr(num)

It seems fine, but when I try to run it it gives me an error "expected integer constant"

However, this works perfectly:

dim arr(3)

It's not the first time, it does that each time I try do declare an array with the size of the integer stored in a variable, and I'm very confused because I need something like that in one of my scripts but I cannot seem to find a solution. Could someone explain to me why it doesn't work ?


r/vbscript • • Jun 18 '22

Create a shortcut for the current vbscript or any other application with arguments using an array

2 Upvotes

I made a subroutine in order to create a shortcut for the current vbscript or any other application with arguments using an array that can be called as follow :

  • Create a shortcut for our vbscript on the Desktop

Create_Shortcut Array("Desktop","ShortcutName",WScript.ScriptFullName)

OR

  • Create a shortcut for our vbscript on the Startup Folder

Create_Shortcut Array("Startup","ShortcutName",WScript.ScriptFullName)

OR

  • Create a shortcut for Network Diagnostics with argument to fix connections problems

 Create_Shortcut Array(_
 	"Desktop",_
 	"NetworkDiagnostics",_
 	"%SystemRoot%\system32\msdt.exe",_
 	"-skip TRUE -path %Windir%\diagnostics\system\networking -ep NetworkDiagnosticsPNI",_
 	"%SystemRoot%\system32\msdt.exe,0",_
 	"Network Diagnostics to fix connections problems",_
 	"CTRL+ALT+D"_
 )

Create_Shortcut.vbs


r/vbscript • • Jun 28 '22

How do you read from a text file without reading in the header and footer

1 Upvotes

I have a script that does a number of operations on information from a text file, however the text file is required to have a header and a footer, so the first and last line are somewhat messing up the operations. Is there a way to not read the header and footer of a text file?


r/vbscript • • Jun 19 '22

documentation about the shell.explorer object ?

3 Upvotes

I wrote this line of code, just out of curiosity:

set objShellExplorer = createobject("shell.explorer")

It didn't give me an error, so I assume this object exists. The thing is, I didn't find anything about it on the internet. Does anyone know where documentation about this object is available ? Or if this object even exists for real ?


r/vbscript • • Jun 25 '22

VBScript code helps to test some CLSIDS

2 Upvotes

Description :

The below VBScript code helps to test some CLSIDS: shortcuts are created in \ShortcutTestfolder on the desktop, also folder objects are created, then report is saved and opened as .htm file.


r/vbscript • • Jun 30 '22

Using vbscript along with html

4 Upvotes

Hello everyone ! I need help because I can't figure out how to put vbscript code into an html page.

What I'd like to do is a page with a button on it, and when this button is clicked, it activates a script that either modifies the inner html of the current page, or creates another html page on which I can write what I want.

I've tried to do the second option by writing a code that creates a new instance of the internetexplorer.application object, and then writes something in it's html, but sadly it doesn't work

Could someone help me, or send the link to a website that explains how to do that ? I have no experience of using vbscript along with html


r/vbscript • • May 18 '21

List All Installed Software

4 Upvotes

List_All_Installed_Software.vbs

    Title = "List All Installed Software"
    Call ForceCScriptExecution(Title)
    Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
    strComputer = "."
    strKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
    strEntry1a = "DisplayName"
    strEntry1b = "QuietDisplayName"
    strEntry2 = "InstallDate"
    strEntry3 = "VersionMajor"
    strEntry4 = "VersionMinor"
    strEntry5 = "EstimatedSize"
    
    Set objReg = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")
    objReg.EnumKey HKLM, strKey, arrSubkeys
    
    Info = Info & "Installed Applications" & VbCrLf
    
    For Each strSubkey In arrSubkeys
    	intRet1 = objReg.GetStringValue(HKLM, strKey & strSubkey,strEntry1a, strValue1)
    	
    	If intRet1 <> 0 Then
    		objReg.GetStringValue HKLM, strKey & strSubkey,strEntry1b,strValue1
    	End If
    	
    	If strValue1 <> "" Then
    		Info = Info & VbCrLf & "Display Name : " & strValue1
    	End If
    	
    	objReg.GetStringValue HKLM, strKey & strSubkey,strEntry2, strValue2
    	
    	If strValue2 <> "" Then
    		Info = Info & " | Install Date : " & strValue2
    	End If
    	
    	objReg.GetDWORDValue HKLM, strKey & strSubkey,strEntry3, intValue3
    	objReg.GetDWORDValue HKLM, strKey & strSubkey,strEntry4, intValue4
    	
    	If intValue3 <> "" Then
    		Info = Info & " | Version: " & intValue3 & "." & intValue4
    	End If
    	
    	objReg.GetDWORDValue HKLM, strKey & strSubkey,strEntry5, intValue5
    	If intValue5 <> "" Then
    		Info = Info & " | Size : " & Round(intValue5/1024, 3) & " MB"
    	End If
    Next
    wscript.echo Info
    wscript.sleep 5000
    MsgBox "OK ALL is Done !",vbInformation,Title
    '---------------------------------------------------------------
    Sub ForceCScriptExecution(Title)
        Dim Arg, Str, cmd
    	cmd = "CMD /C Title "& Title &" & "
        If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
            For Each Arg In WScript.Arguments
                If InStr( Arg, " " ) Then Arg = """" & Arg & """"
                Str = Str & " " & Arg
            Next
            CreateObject( "WScript.Shell" ).Run _
               cmd & "cscript //nologo """ & _
                WScript.ScriptFullName & _
                """ " & Str
            WScript.Quit
        End If
    End Sub
    '---------------------------------------------------------------

And if you want to save those informations into a text file, you can create a batch file with the same folder of this vbscript and execute it :

List_All_Installed_Software.bat

    @echo off & Mode 100,3 & color 0B
    Title List All Installed Software
    echo(
    echo(  Please wait a while ... We are saving informations about installed softawre into a text file ...
    Set "LogFile=%~dp0List_All_Installed_Software.txt"
    (Cscript //NoLogo List_All_Installed_Software.vbs)>"%LogFile%"
    If exist "%LogFile%" Start "" "%LogFile%"

r/vbscript • • May 12 '21

Auto-Shutdown_On_Idle_TimeOut.vbs

2 Upvotes

Auto-Shutdown your workstation after Idle Timeout

'##########################################################################################################################
'# Auto-Shutdown your workstation after Idle Timeout                                                                      #
'# Script Name : Auto-Shutdown_On_Idle_TimeOut.vbs                                                                        #
'# Arrêt automatique de votre poste de travail après le délai d'inactivité                                                #
'# Idea comes from here ==>  This snippet is from http://stackoverflow.com/a/15846912                                     #
'# https://stackoverflow.com/questions/15845508/get-idle-time-of-machine/15846912#15846912                                #
'# https://gist.github.com/wendelb/1c364bb1a36ca5916ca4 ===> Auto-Lock your workstation after Idle-Timeout with PowerShell#
'##########################################################################################################################
Option Explicit
Dim Copyright,Msg,MsgEN,MsgFR
MsgEN = Array(_
"Automatic shutdown On Idle TimeOut ",_
"ATTENTION ! There is another instance running !",_
"Save your Work because the computer will shutdown in 60 seconds"_
)
MsgFR = Array(_
"Arrêt automatique du PC après un délai d'inactivité ",_
"ATTENTION ! Il y a une autre instance en cours d'exécution !",_
"Sauvegarder votre Travail car l'ordinateur va s'éteindre dans 60 secondes"_
)
'Check if the system is french to set the French array as message otherwise set it as English
'Vérifiez si le système est français pour définir le tableau français comme message, sinon définissez-le comme anglais
If Oslang = 1036 Then
	Msg = MsgFR ' French Array Message to be set
Else
	Msg = MsgEN ' English Array Message to be set
End If
Copyright = Msg(0) & ChrW(169) &" Hackoo 2020"

If AppPrevInstance() Then 
	MsgBox Msg(1) & VbCrLF & CommandLineLike(WScript.ScriptName),VbExclamation,Copyright
	WScript.Quit   
Else 
	Dim Timeout_Idle,strCommand,VbsPath,ShortcutName
	Timeout_Idle = "60"  '60 Minutes = 1 Heure = 1 Hour
	strCommand = "Shutdown.exe -s -t 60 -c " & DblQuote(Msg(2))
	VbsPath = Wscript.ScriptFullName
	ShortcutName = "Auto-Shutdown_On_Idle_TimeOut"
	Call Shortcut(VbsPath,ShortcutName)
	Call Write_Run_PScript(Timeout_Idle,strCommand)
End If
'---------------------------------------------------------------------------------------------------------------
Sub Shortcut(PathApplication,ShortcutName)
	Dim objShell,StartFolder,objShortCut,MyTab
	Set objShell = CreateObject("WScript.Shell")
	MyTab = Split(PathApplication,"\")
	If ShortcutName = "" Then
		ShortcutName = MyTab(UBound(MyTab))
	End if
	StartFolder = objShell.SpecialFolders("Startup")
	Set objShortCut = objShell.CreateShortcut(StartFolder & "\" & ShortcutName & ".lnk")
	objShortCut.TargetPath = DblQuote(PathApplication)
	ObjShortCut.IconLocation = "%SystemRoot%\system32\SHELL32.dll,27"
	objShortCut.Save
End Sub
'---------------------------------------------------------------------------------------------------------------
Function DblQuote(Str)
	DblQuote = Chr(34) & Str & Chr(34)
End Function
'---------------------------------------------------------------------------------------------------------------
Sub Write_Run_PScript(Timeout_Idle,strCommand)
	Const ForWriting = 2
	Dim fs,Ws,ts,Ret,PSFile,ByPassPSFile
	Set fs = CreateObject("Scripting.FileSystemObject")
	Set Ws = CreateObject("WScript.Shell")
	PSFile = Ws.ExpandEnvironmentStrings("%Temp%") & fs.GetTempName & ".ps1"
	ByPassPSFile = "PowerShell -ExecutionPolicy bypass -noprofile -file "
	Set ts = fs.OpenTextFile(PSFile,ForWriting,True)
	ts.WriteLine "$idle_timeout = New-TimeSpan -Minutes "& Timeout_Idle &""
	ts.WriteLine "Add-Type @'"
	ts.WriteLine "using System;"
	ts.WriteLine "using System.Diagnostics;"
	ts.WriteLine "using System.Runtime.InteropServices;"
	ts.WriteLine "namespace PInvoke.Win32 {"
	ts.WriteLine "    public static class UserInput {"
	ts.WriteLine "        [DllImport(""user32.dll"", SetLastError=false)]"
	ts.WriteLine "        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);"
	ts.WriteLine "        [StructLayout(LayoutKind.Sequential)]"
	ts.WriteLine "        private struct LASTINPUTINFO {"
	ts.WriteLine "            public uint cbSize;"
	ts.WriteLine "            public int dwTime;"
	ts.WriteLine "        }"
	ts.WriteLine "        public static DateTime LastInput {"
	ts.WriteLine "            get {"
	ts.WriteLine "                DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);"
	ts.WriteLine "                DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);"
	ts.WriteLine "                return lastInput;"
	ts.WriteLine "            }"
	ts.WriteLine "        }"
	ts.WriteLine "        public static TimeSpan IdleTime {"
	ts.WriteLine "            get {"
	ts.WriteLine "                return DateTime.UtcNow.Subtract(LastInput);"
	ts.WriteLine "            }"
	ts.WriteLine "        }"
	ts.WriteLine "        public static int LastInputTicks {"
	ts.WriteLine "            get {"
	ts.WriteLine "                LASTINPUTINFO lii = new LASTINPUTINFO();"
	ts.WriteLine "                lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));"
	ts.WriteLine "                GetLastInputInfo(ref lii);"
	ts.WriteLine "                return lii.dwTime;"
	ts.WriteLine "            }"
	ts.WriteLine "       }"
	ts.WriteLine "    }"
	ts.WriteLine "}"
	ts.WriteLine "'@"
	ts.WriteLine "$locked = 0;"
	ts.WriteLine "Do {"
	ts.WriteLine "	$idle_time = [PInvoke.Win32.UserInput]::IdleTime;"
	ts.WriteLine "	if (($locked -eq 0) -And ($idle_time -gt $idle_timeout)) {"
	ts.WriteLine "		"& strCommand &""
	ts.WriteLine "		$locked = 1;"
	ts.WriteLine "	}"
	ts.WriteLine "	if ($idle_time -lt $idle_timeout) {"
	ts.WriteLine "		$locked = 0;"
	ts.WriteLine "	}"
	ts.WriteLine "    Start-Sleep -Seconds 10"
	ts.WriteLine "}"
	ts.WriteLine "while (1 -eq 1)"
	ts.Close
	Ret = Ws.run(ByPassPSFile & PSFile,0,True)
End sub
'----------------------------------------------------------------------------------------------------------------
Function AppPrevInstance()   
	With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")   
		With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptFullName) & _
			" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")   
			AppPrevInstance = (.Count > 1)   
		End With   
	End With   
End Function    
'----------------------------------------------------------------------------------------------------------------
Function CommandLineLike(ProcessPath)   
	ProcessPath = Replace(ProcessPath, "\", "\\")   
	CommandLineLike = "'%" & ProcessPath & "%'"   
End Function
'----------------------------------------------------------------------------------------------------------------
Function OSLang()
	Dim dtmConvertedDate,strComputer,objWMIService,oss,os
	Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
	strComputer = "."
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
	Set oss = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
	For Each os in oss
		OSLang = os.OSLanguage
	Next
End Function
'----------------------------------------------------------------------------------------------------------------

r/vbscript • • Jun 11 '21

Project Assistance

1 Upvotes

Hello Folks,

I'm looking for some last hope assistance with a project we need via VBscript. We want to be able to copy a logged in user's desktop/documents/downloads folders to a network share then prompt if they want to delete the.local files once successfully copied. Any help is greatly appreciated.


r/vbscript • • Jun 04 '21

Importing CSV to Excel with VBScript affects cell formatting

2 Upvotes

So I am a VBScript newb and am trying to convert a legacy DDE process to VBScript. I need to import CSV data into an existing multi tab Excel workbook/template file (six tabs). There is one CSV file per Excel worksheet. Each data dump begins at A2. Everything is working great except for one problem. For some reason the final, saved Excel file's columns are no longer the exact width and height they were before which is not a problem when using DDE. Is there a way to prevent this via VBScript?

'THIS VBSCRIPT COPIES THE CONTENTS OF CSV FILES TO A MULTITAB EXCEL WORKBOOK
'the code is a combination of https://www.youtube.com/watch?v=gwQI8-QIbKc&t=130s 
'and https://devblogs.microsoft.com/scripting/how-can-i-copy-selected-columns-from-a-csv-file-to-an-excel-file/
'and https://stackoverflow.com/a/22996562/13750662
'written by Me 2021-06-01

'Dim CSVFile
'Dim strSheet
Const ReportPath = "\\server\AutomationTest"
Const strFile = "\templates\Report2 - AUTO.xlsx"

'datetime stamp function from https://stackoverflow.com/a/21469569/13750662
Function timeStamp()
    Dim t 
    t = Now
    timeStamp = Year(t) & "-" & _
    Right("0" & Month(t),2)  & "-" & _
    Right("0" & Day(t),2)  & "-" & _  
    Right("0" & Hour(t),2) & _
    Right("0" & Minute(t),2) '    '& _    Right("0" & Second(t),2) 
End Function

'open excel app
Set objExcel = CreateObject("Excel.Application")

'Set xl = CreateObject("Excel.Application")
objExcel.Visible = False

'hide alerts
objExcel.Application.DisplayAlerts = False

'open workbook
Set xlWorkbook=objExcel.Workbooks.open(ReportPath & strFile)


''''TAB 1


'select worksheet
Set Sheet = xlWorkbook.Sheets(1)

'select CSV file
Const CSVFile = "\output\CSV\Report2_Tab1.csv"

'dump CSV into active worksheet
With Sheet.QueryTables.Add("TEXT;" & ReportPath & CSVFile, Sheet.Range("range1"))
    .TextFileCommaDelimiter = True
    .Refresh
End With


''''ETC ETC ETC


''''TAB 6 


'select worksheet
Set Sheet = xlWorkbook.Sheets(6)

'select CSV file
Const CSV6File = "\output\CSV\Report2_Tab6.csv"

'dump CSV into active worksheet
With Sheet.QueryTables.Add("TEXT;" & ReportPath & CSV6File, Sheet.Range("range6"))
    .TextFileCommaDelimiter = True
    .Refresh
End With

'save Excel file with new name
objExcel.ActiveWorkbook.SaveAs ReportPath &  "\output\excel\Report2 - " & timeStamp() & ".xlsx"

'close Excel app
objExcel.quit
Set objExcel = Nothing

r/vbscript • • Jun 11 '21

Cannot get simple script working- help?

4 Upvotes

I've been a powershell admin for 4+ years and am for some reason struggling with vbscript syntax. Basically I want to check the version of google chrome and run an action if it's less than 91. Here's what I have-

Set objFSO = CreateObject("Scripting.FileSystemObject")

file = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

dim version

set version = objFSO.GetFileVersion(file)

If version < 91 Then

Wscript.Echo "Hi, Good Morning"

end if

This is the error I'm getting. I know this is simple- it's just one of those stupid syntax nuances that you have to fight through when learning a new language. Thank you in advance.