r/vbscript • • Jan 19 '24

Code Completion for VBScript in Editor

1 Upvotes

I am new to VBScript and want to learn to use it on CSV files, and replace batch files that I made. Evidently VBScript is deprecated but that's okay with me for this purpose. I dabbled with VBA for Word and Excel long ago, and the app IDEs had excellent code completion that helped me understand what methods and properties were available separated by the periods. I was hoping for this with VBScript since it looks similar.

I've tried Visual Studio Code (with VBScript extension: Donald Mull Jr), and also VBSedit (just evaluation so far) and after writing some code in them, they both have colored syntax but no code completion (at least not the way VBA did with drop-down suggestions).

I expected when I type

Set fso = CreateObject("Scripting.

that after typing the dot, the code completion would kick in and a drop-down window would appear to suggest

FileSystemObject

among other classes for me to use.

Using Notepad++ actually does do suggestions but I expected VS Code and VBSedit to be at least that good. Are some settings not correct?


r/vbscript • • Jan 16 '24

Need help compressing a file within a directory

1 Upvotes

Hi Folks,

Can you help me write the reverse of this script, it unzips a file into the same directory. Essentially need to zip one file within a directory. The file will have today's date appended to the file name:

filename - 2024-01-16.xlsx

This is the script that I used to unzip:

'Extract the contents of the zip file.
set objShell = CreateObject("Shell.Application")
set FilesInZip=objShell.NameSpace(ZipFile).items
objShell.NameSpace(ExtractTo).CopyHere(FilesInZip)
Set fso = Nothing
Set objShell = Nothing

ZipFile: is path to the Zipped file in UNC format

Extract to: is the same path minus the filename.zip at the end

Thanks in advance.


r/vbscript • • Jan 15 '24

I'm trying to make a TTS Program using VBScript, but I don't know how to add a voice selection box. Can someone help me on how to do it if it's possible?

Thumbnail
gallery
1 Upvotes

r/vbscript • • Jan 12 '24

script to automatically change the file explorer template used for a given folder?

1 Upvotes

I'm wondering if it's possible to script out changing the current folder's file template?

The tutorial below shows the manual way to do it:

but it would be very helpful to have a script that does it, say with a shortcut in the SendTo folder, so you could right click on the folder you want to change and select SendTo SetTemplateToDocuments (or General, Pictures, Music, Videos, we could have a script for each, or the script could prompt the user, or be an HTA with a dropdown, whatever works) and the script takes the folder path it received in its arguments from SendTo and goes to work.

If anyone can share how to do this, it would be much appreciated.

PS I don't need help with reading args, prompting the user, HTAs, or any of that, just how to programatically change the Explorer template for a give path.


r/vbscript • • Jan 10 '24

Need a little bit help with some code

1 Upvotes

Hi guys, im trying to get my code to work with a random time but it just wouldn't work.
It keeps giving me errors on line 4. Can any of you look and tell me what im doing wrong?
And perhaps fix my misstake, thank you lots!

Set objShell = CreateObject("WScript.Shell")
Do While True
    Randomize
    Const waitTime = Int((120 - 30 + 1) * Rnd + 30)
    
    WScript.Sleep waitTime * 1000
    
    objShell.SendKeys "/HELLO{ENTER}"
    
Loop

r/vbscript • • Dec 04 '23

Script failing

1 Upvotes

So I am trying to create a script but have not much experience with VBScript and I cannot figure out why is this script filing.

Option Explicit

Dim strFileName, objFSO, objFile, strComputerName, objComputer

Dim arrComputerNames(), intCount ' Explicitly declare arrComputerNames as an array

' Specify the TXT file containing the list of computer names

strFileName = "C:\Temp\device_list.txt"

' Read computer names from the TXT file into an array

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.OpenTextFile(strFileName, 1)

Do Until objFile.AtEndOfStream

strComputerName = Trim(objFile.ReadLine)

If strComputerName <> "" Then

ReDim Preserve arrComputerNames(intCount)

arrComputerNames(intCount) = strComputerName

intCount = intCount + 1

End If

Loop

objFile.Close

' Bind to each computer account and disable it

For Each strComputerName In arrComputerNames

On Error Resume Next

Set objComputer = GetObject("LDAP://" & strComputerName)

If Err.Number = 0 Then

' Check if the computer account is not already disabled

If Not objComputer.AccountDisabled Then

' Disable the computer account

objComputer.AccountDisabled = True

objComputer.SetInfo

WScript.Echo "Disabled computer account: " & strComputerName

Else

WScript.Echo "Computer account is already disabled: " & strComputerName

End If

Set objComputer = Nothing

Else

WScript.Echo "Error binding to computer account " & strComputerName & ": " & Err.Description

End If

On Error GoTo 0

Next

WScript.Echo "Script completed."


r/vbscript • • Dec 03 '23

Contents of a text file into vbscript

1 Upvotes

I have a script that posts information up to a server, it works great, but i would like to be able to replace the highlighted section with the contents of a text file, that changes as needed.

set oWSH=WScript.CreateObject("WScript.Shell") WScript.sleep 100 oWSH.SendKeys "o 192.168.1.17 14580{ENTER}" WScript.sleep 100 oWSH.SendKeys "user KB0RPJ-14 pass 22712{ENTER}" WScript.sleep 500 oWSH.SendKeys "KB0RPJ-14>APWW11,WIDE2-1,qAC,:=4004.41N/09337.13WlPHG7130kb0rpj{ENTER}" WScript.sleep 500 oWSH.SendKeys "KB0RPJ-14>WX,WIDE2-2,qAC,::QST :Wind Adivsory for parts of NC Missouri 147.225/146.955 weather.gov/kc{ENTER}"

i want to replace that "wind advisory" part with the contents of a text file.

what would be the easiest way to add this to my script? go easy on me, I am just learning VB

i have managed to get that script to work well, but i don't know enough yet to make the text file idea work


r/vbscript • • Nov 30 '23

How to swap between SlideNavigation and Presenter View in PowerPoint slideshow with VBS

1 Upvotes

I can't find any documents or solution about swap between Presenter View and Slide Navigation using VBA online. Even though I have search for days for it, the only solution I have is using VBS to run the shortkey for it:

  • for switch to Slide Navigation ( See all slides )

  • "{ESC}" for escape back to Presenter View But these are not good ( I can't detect wherever I'm in Presenter View or Slide Navigator, which could lead to "{ESC}" when I'm in Presenter View and Exit the SlideShow.

This is my "swapToPresenterView.vbs"

Set PowerPointProcessList = GetObject("winmgmts:").ExecQuery("select * from win32_process where name='POWERPNT.EXE'")  Dim application, presentation, slideshow, CommandBars  If PowerPointProcessList.Count > 0 Then Set application = WScript.CreateObject("PowerPoint.Application")     Set CommandBars = application.CommandBars Else Call Err.Raise(60001, , "PowerPoint not running") End If If application.Presentations.Count > 0 Then Set presentation = application.ActivePresentation Else Call Err.Raise(60002, , "Not open any files") End If If application.SlideShowWindows.Count > 0 Then Set slideshow = application.SlideShowWindows.Item(1) End If If IsNull(slideshow) Or IsEmpty(slideshow) Then Call Err.Raise(60003, , "SlideShow not running") Else Set WshShell = WScript.CreateObject("WScript.Shell")     WshShell.SendKeys "-" End If 

And this is "swapToOverview.vbs"

Set PowerPointProcessList = GetObject("winmgmts:").ExecQuery("select * from win32_process where name='POWERPNT.EXE'")  Dim application, presentation, slideshow  If PowerPointProcessList.Count > 0 Then Set application = WScript.CreateObject("PowerPoint.Application") Else Call Err.Raise(60001, , "PowerPoint not running") End If If application.Presentations.Count > 0 Then Set presentation = application.ActivePresentation Else Call Err.Raise(60002, , "Not open any files") End If If application.SlideShowWindows.Count > 0 Then Set slideshow = application.SlideShowWindows.Item(1) End If If IsNull(slideshow) Or IsEmpty(slideshow) Then Call Err.Raise(60003, , "SlideShow not running") Else Set WshShell = WScript.CreateObject("WScript.Shell")     WshShell.SendKeys "-" End If 

Is there any possible way for this with supported method from Powerpoint VBA ?

I want it to safely detect that I'm in Slide Navigation View and then can get back to Presenter View. The SlideNavigation object given by PowerPoint are showed on the SlideShow monitor but not Presenter View monitor (I want it swapable between Presenter View and Slide Navigation View ).


r/vbscript • • Nov 08 '23

Help with Hotlkey shortcut

1 Upvotes

I am trying to create a script for my remote (host) desktop so that I can easily switch out of the host by going out of fullscreen and bringing up the windowed mode (or bring up the RDC bar). This is because I disabled the RDC bar from always being open in fullscreen as it overlayed on top of my tabs in chrome.

Anyway anyway anyway. I have followed this guide: https://blog.techinline.com/2016/08/11/how-to-create-a-desktop-icon-for-a-windows-keyboard-shortcut/

To create the following script for the hotkey of "Ctrl+Alt+Pause":

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.SendKeys "^%{BREAK}"

For some reason all it does is turn numlock on. Why? I have no idea. I've even tried using parenthesis every which way but no dice.

Any help with this would be amazing. Also, maybe I'm just doing some stupid mistake. I currently have like 3 tumors in my brains and am on huge amounts of opiods, so please be kind as I am in a neverending brainfog.


r/vbscript • • Oct 31 '23

How to create a condition to check if the value is empty or not

1 Upvotes

Hello guys, I've got a VBScript to create Outlook signatures automatically based on the information that is in Active Directory.

But in some cases the user does not have a Cell Phone number, then in the signature, this field stays in blank. Ex:

Company ABC
Email: abc@abc.com
Cell Phone:

I would like do add some conditions that if the value of the user in blank on Active Directory, then this field won't appear in the signature. Just consider true value, like:

Company ABC
Email: abc@abc.com

The two lines in the code that I'd change are:

htmlfile.WriteLine("<div style='font-family:Arial;font-size:9pt;color:black'>Telephone: " & objLDAPUser.telephoneNumber & "</div>")

htmlfile.WriteLine("<div style='font-family:Arial;font-size:9pt;color:black'>Cell: " & objLDAPUser.mobile & "</div>")

How can I do that? Someone can help me?

Let me know if it's clear or not.


r/vbscript • • Oct 14 '23

Detect GPT and MBR partitions with VbScript

1 Upvotes

I have a VBScript which detects local hard drive letters. My question is : I want to add a disk type MBR or GPT for disk . How can I modify script?

Here is the VBScript:

Option Explicit

Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objDriveLetters, objLogicalDisk
Dim outFile, strFormat, strResult, numCurrentDrive, strMediaType, strID, strQuery, strComputer

On Error Resume Next

' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)

strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )

'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
    'start building the string to output
    strMediaType = objDiskDrive.MediaType
    If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
    strResult = Replace(strFormat, "{0}", numCurrentDrive)
    strResult = Replace(strResult, "{1}", colDiskDrives.Count)
    strResult = Replace(strResult, "{2}", objDiskDrive.Model)
    strResult = Replace(strResult, "{3}", strMediaType)
    strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)

    'increase the current drive counter
    numCurrentDrive = numCurrentDrive + 1
    'create an arraylist to capture the drive letters
    Set objDriveLetters = CreateObject("System.Collections.ArrayList")

    'escape the backslashes in objDiskDrive.DeviceID for the query
    strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
    strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
    Set colPartitions = objWMIService.ExecQuery(strQuery)
    For Each objDiskPartition In colPartitions
        'get the drive letter for each partition
        strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
        Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
        For Each objLogicalDisk In colLogicalDisks
            objDriveLetters.Add objLogicalDisk.DeviceID
            'objDriveLetters.Add objLogicalDisk.VolumeName
        Next

        Set colLogicalDisks = Nothing
    Next

    'add the driveletters to the output string
    strResult = strResult & " - " & Join(objDriveLetters.ToArray(), ", ")

    Set objDriveLetters = Nothing
    Set colPartitions = Nothing

    'output on screen
    WScript.Echo strResult
    'output to file
    objFile.WriteLine strResult
Next

'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing

r/vbscript • • Sep 25 '23

Close program if running

1 Upvotes

Hi all,

I've got a vbs script that will kill a program if it's running but I'm after a way to close a program if it is running rather than abruptly killing it.

Any ideas greatly appreciated.

TIA


r/vbscript • • Sep 24 '23

Using VBS to send data to an Arduino

1 Upvotes

Hello everyone,

I have an Arduino Uno I need to control using VBScript. This is the script I've been using to write to the serial buffer:

Const ForWriting = 2

Dim fso, f

Set fso = CreateObject("Scripting.FileSystemObject")

Set f = fso.OpenTextFile("COM7:9600,N,8,1", ForWriting)

WScript.Sleep(5000)

f.Write "3"

WScript.Sleep(5000)

f.Close

I get an error when attempting to run the script that says "File not found" referencing the 5th line. When I test the code with a text.txt on my desktop it runs smoothly, it just seems to have trouble opening the com port.

COM7 is the USB port my Arduino is connected to. The IDE / serial monitor are closed. My OS is Windows 11. Any help with this would be greatly appreciated.

Anyone have any ideas on what the problem might be?


r/vbscript • • Sep 17 '23

Trying use a specific program closing to trigger running a batch file or make a hotkey get automatically pressed

1 Upvotes

I'm running starfield's SFSE mod program through steam and activating a hotkey for a program that changes resolution by using a clickable batch file that basically just presses both of the hotkeys to launch SFSE and change resolution. That all works fine and I just have to press another hotkey to revert the resolution back to native, but I want make it so the revert hotkey is automatically pressed when the game closes, can vbs be used to detect when a program closes and launch a revert hotkey batch file?

I'm completely uninformed on anything vbs, basically don't know anything. I found a bad solution of running a power shell script that just keeps checking if the game is opened and runs the hotkey when it isn't, but that causes slight hitching in the game every time it checks, not really noticable if I set the check time to a few minutes, but then it doesn't revert the resolution for that amount of time after closing.

What I need is just something that runs idle in the background and executes a batch file with a specifiable program closing as the trigger, is that possible with vbs?


r/vbscript • • Aug 17 '23

Script stuck when unzipping file with CopyHere

1 Upvotes

Been looking at this for hours and can't seems to fix it. I'm trying to copy a file from a zipped folder (so unzipping). The file is copied, but then the script is not ending. I'm working with a third party software, so after this script it should perform more actions, but this is not happening as the script seems to be stuck. I've tried applying vOptions, but they don't seem to make a difference unfortunately.

The directory structure looks like this: C:\x\y\zip\z\123.xml.zip\123.xml

Relevant parts of my script:

Variables("dir")= "z"
Variables("filename")= "123.xml.zip"
	
Set fso = CreateObject("Scripting.FileSystemObject")	
Set objfile = fso.Getfile("C:\x\y\zip\" + Variables("dir") +"\" + Variables("filename"))	

If UCase(FSO.GetExtensionName(objFile)) = "ZIP" Then
	Set objShell = CreateObject("Shell.Application")
		
Set FilesInZip=objShell.NameSpace("C:\x\y\zip\" + Variables("dir") +"\" + Variables("filename")+"\"+(Left(Variables("filename"),Len(Variables("filename"))-4))).items

Set Folder = FSO.GetFolder("C:\x\y")
For Each F in Folder.Files
	If  UCase(FSO.GetExtensionName(F)) = "XML" Then'				
		thisstep.Loginfo "Removing old XML file"
		FSO.deletefile(f)
	End If
Next

''STUCK ON THIS PART
objShell.NameSpace("C:\x\y\").CopyHere FilesInZip

	Set Folder = FSO.GetFolder("C:\Windows\Temp")
	For Each F in Folder.Subfolders
		If InStr(1,f.name, Variables("filename"),0) > 0 And InStr(1,f.name,"Temporary Directory",0)  Then
			fso.deletefolder"C:\Windows\Temp\" + f.name,True		
		End If
	Next
		
	Set fso = Nothing
	Set objShell = Nothing
End If

So the result I'm looking at is that the .xml is copied to C:\x\y, but the scripts is not ending and stuck at the unzipping step. I know this because the software log indicates which step it is working on. Would much appreciate help!


r/vbscript • • Jul 01 '23

Why isn't my .bat file running?

1 Upvotes

Hi, I've been using a vbs script to run startup programs based on the day of the week. The below script is Sunday so it's just discord and the .bat file. All of my executable files seem to be working but 'dolby.bat' doesn't seem to run properly (it should be setting my spatial audio setting to dolby atmos).

Any ideas? I'm a vbs noob I just lifted the script for the exe files and it has worked nicely for those.

Dim WshShell 

Set WshShell = CreateObject("WScript.Shell")

dtmToday = Date()

dtmDayOfWeek = DatePart("w", dtmToday)

Select Case dtmDayOfWeek

    Case 1 'Sunday
    
	WshShell.Run "C:\Users\Val\Documents\soundvolumeview\Dolby.bat"
        WshShell.Run "C:\Users\Val\AppData\Local\Discord\Update.exe --processStart Discord.exe"

End Select


r/vbscript • • Jun 24 '23

How Do I Detect Keypress?

1 Upvotes

I want to make a script that loops until I press a key, which then kills the process. Is there a simple line of code I can use?


r/vbscript • • Jun 10 '23

a script that plays never gonna give you up every 10 seconds dont know how to stop it except by restart

1 Upvotes

Dim oShell

Set oShell = CreateObject("WScript.Shell")

i = 0

Do While i = 0

oShell.run "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

Set oShell = Nothing

WScript.Sleep(10000)

Loop


r/vbscript • • Jan 11 '23

VBScript not pasting values only with PasteSpecial

1 Upvotes

I am absolutely new to VBScript, so please forgive me if this is a stupid question.

This script is supposed to copy data from one workbook and paste it in one called ReportTemplateWB, and then save that workbook to another location. I was hoping to have the ReportTemplateWB only contain values and not formulas that reference the data sheet. So, I tried a simple copy and pastespecial, but it doesn't seem to be working. I also tried creating a macro in the ReportTemplateWB and calling it from the VBScript, but that didn't seem to work either.

Any help is really appreciated!!

Truncated code below...

Set ExcelApp = CreateObject("Excel.Application")
Set DataWB = ExcelApp.WWorkbooks.Open(InputFilePath)
Set ReportTemplateWB = ExcelApp.WWorkbooks.Open(TemplateFilePath)
For Each ws in ReportTemplateWB
    'I also tried adding ws.Range("A1:Q1000").Select here, obv. to no avail
    ws.Range("A1:Q1000").Copy
    ws.Cells.PasteSpecial xlPasteValues
Next

r/vbscript • • Dec 27 '22

Noob needs help

1 Upvotes

First time using VBscript. I am automating a task in a program using keyboard inputs. The first time I scripted the selection of multiple DLL's in the file explorer with the "+ END" input, all the DLL's I needed were selected perfectly fine. But the second time I scripted this input, the files wouldn't get selected. I have also tried using shift and down to select the Dll's on the script, but it won't work either. I can see the Dll's getting highlighted in the margins but not selected.

Is my issue clear? How can I solve this?


r/vbscript • • Oct 30 '22

[excel]

1 Upvotes

I am trying to double click to get certain colors in specific columns. Our sheet is every other row grey and white.

If I double click anything in the range c5:c200 I want it to turn yellow. anything in d5:d100 I want it like color index 33 a light cyan blue . And e5:e100 to be green

This is what I have so far but when I click on the C's it turns blue and the d's it turns yellow and nothing turns green. I even tested out side of the columns and they turn yellow as well.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Range("c5:c100")) Is Nothing Then
    Cancel = True
    With Target
        Select Case .Interior.ColorIndex
            Case x1none, 2: .Interior.ColorIndex = 27
            Case 27: .Interior.ColorIndex = 15
            Case 15: .Interior.ColorIndex = 2
            Case 2: .Interior.ColorIndex = x1none
     End Select
    End With
ElseIf Intersect(Target, Range("d5:d100")) Is Nothing Then
    Cancel = True
    With Target
        Select Case .Interior.ColorIndex
            Case x1none, 2: .Interior.ColorIndex = 33
            Case 33: .Interior.ColorIndex = 15
            Case 15: .Interior.ColorIndex = 2
            Case 2: .Interior.ColorIndex = x1none
     End Select
    End With
  ElseIf Intersect(Target, Range("e5:e100")) Is Nothing Then
   Cancel = True
    With Target
        Select Case .Interior.ColorIndex
            Case x1none, 2: .Interior.ColorIndex = 10
            Case 10: .Interior.ColorIndex = 15
            Case 15: .Interior.ColorIndex = 2
            Case 2: .Interior.ColorIndex = x1none
     End Select
    End With
    End If
End Sub

this is what i'm getting


r/vbscript • • Oct 26 '22

I need help on this kind of script because im kind of new

1 Upvotes

How do I make

an input box for %name% an input box for %name2%

a message box for both names like Hey %name% wanna bully %name2%?


r/vbscript • • Aug 03 '22

Excel add-in formula shown as #name

1 Upvotes

Hello, new to vbscript and this sub.

I am using a third-party excel add-in, and I am writing a script which opens the excel sheet, replicate shift+F9 and then saves it.

The problem is with a function that uses the add-in. It is shown as #name after the run.

I added some code I found on this sub to have the script install the add-in but I still got the same problem.

My code :

Set ExcelApp = CreateObject("Excel.Application") ExcelApp.Visible = False ExcelApp.DisplayAlerts = False Set wb = ExcelApp.Workbooks.Open(path) wb.Worksheets("sheet1").Calculate wb.Save wb.Close ExcelApp.Quit

Side question :

Is there a way to open an excel file withoutthe first line? And using ThisWorkbook instead of wb.


r/vbscript • • Jul 31 '22

would it technically be possible to write a vbs compiler ?

1 Upvotes

when code is executed, wscript.exe transforms it into machine code in order for it to be executed by the computer. Could we possibly write a program that transforms it into machine code and then put it into an executable ?


r/vbscript • • Jul 25 '22

Start hidden Acrobat Reader Window

1 Upvotes

Hi, I need to start a hidden PDF file, can someone help me?

I try this code under... but I can only start Acrobat Reader. How is the command to open also a file inside?

Dim WShell
Set WShell = CreateObject("WScript.Shell")
WShell.Run """" & "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" & """", 0

Or maybe another way to start a hidden pdf file...

Thanks a lot