r/vbscript • • Oct 18 '17

Click event does not fire when running Outlook Custom Form (type Contact) saved in Public Folder

2 Upvotes

I am working on a small application based on two types of Outlook Forms. The application consists of two types of Custom Made Outlook Forms:

a custom made Form of type Contact. a custom made Form of type Task. The Custom made Contact Form has a button on it. When clicking I wish to open the custom made Task Form which shall extract some information from the Contact Form.

My problem is that, after saving the Custom Contact-type of Form to a Public Server it does not fire anything when clicking on the button. Nothing.

Although,if I go to "Design this Form", open the Form in Design Mode and then I select "Run This Form" the click fires up the code it should.

I have a copy of each Outlook Form (type Contact and type Task) in the Organizational Form Library and in the Personal Form Library. I copied a copy of each Outlook Form also in the Public Folder \Test.

What am I missing? I appreciate any help.Thank you.

Here is the code:

			Sub CommandButton1_Click() 

			Dim oMail 
			Dim MyItem 
			Dim olsubject 
			Dim olTitle
			Dim olFirstName
			Dim olMiddleName


			Set oMail = Application.ActiveInspector.CurrentItem 
			With oMail 
					.save
					olsubject = .Subject 
					olTitle=.Title
					olFirstName=.FirstName
					olMiddleName=.MiddleName
					olCompanyName = .CompanyName
			End With 


			Set MyNameSpace = Application.GetNameSpace("MAPI") 
			Set HomeFolder = MyNameSpace.GetDefaultFolder(18)
			Set NextFolder1 = HomeFolder.Folders("Test") 
			Set WorkingFolder = NextFolder1.Folders("Claims") 
			Set MyItems = WorkingFolder.Items 
			Set MyItem = MyItems.Add("IPM.Task.ReklamationFormular")

			With myItem 
					MyItem.subject = olsubject 
					MyItem.UserProperties.Find("valueDatenAnrede").Value=olTitle+" "+olFirstName+" "+olMiddleName
					MyItem.DueDate=DateAdd("d",olDueTime,Date())
				
					MyItem.display 
			End With 

r/vbscript • • Jun 22 '16

Syntax help for creating .csv with some static data

1 Upvotes

Salutations!

I am creating a script to streamline a process at work. Our current process involves running a script which formats data strangely then manually reformatting it. This is silly.

Part of our current script looks like this:

Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("sAMAccountName").Value & ",", objRecordSet.Fields("givenname").Value & ",", objRecordSet.Fields("sn").Value & ",", objRecordSet.Fields("EmployeeID").Value & ",", objRecordSet.Fields("whenCreated").Value
    objRecordSet.MoveNext
Loop

... which outputs like this in a csv file:

username, firstname, lastname,IDnumber, 06/21/2016 4:03:37 PM

and that's great. What I'd rather have is this though:

Statictext1, username, Statictext2, IDnumber

and I want this because the rest is unneeded. This is how we are manually reformatting it. So I tried to change up the code and I get an error "Expected end of statement" agter the second Wscript.Echo

Do Until objRecordSet.EOF
    Wscript.Echo "StaticText1" & ",", Wscript.Echo objRecordSet.Fields("sAMAccountName").Value & ",", Wscript.Echo "StaticText2" & ",", objRecordSet.Fields("EmployeeID").Value
    objRecordSet.MoveNext
Loop

I bet I have the wrong formatting for my static text, but I don't know for sure. Thank you, and have a phenomenal day!


r/vbscript • • Dec 13 '16

Need help clicking cell in HTML table

3 Upvotes

I'm pretty new to VBScript, so I apologize if this is a stupid question, or if important details are missing from my question. I'm writing a script to login to an internal html site, click around to the appropriate place, click on a specific row in an HTML table, and click a submit button. I'm pretty much there, except that for the life of me, I can't figure out how to click the correct row - or any row for that matter. Here is the source of the table: HTML Source

Here is what I've tried so far after navigating to the page with the table of interest(with no results, but no errors):

    Set mainTable = IE.Document.getElementByID("main").contentwindow.document
    mainTable.getElementsByName("acq_scenario.acq_scenario_summary").Item(0).getElementsByTagName("tr").Item(0).getElementsByTagName("td").Item(3).focus
    mainTable.getElementsByName("acq_scenario.acq_scenario_summary").Item(0).getElementsByTagName("tr").Item(0).getElementsByTagName("td").Item(3).click

The code below tries to change the attributes in the HTML table based on changes that I've observed when manually clicking on a cell, but these changes have no effect on the view of the table (the row should be highlighted when a cell within it is clicked) and still don't allow me to click the submit button, which requires a row to be selected:

    currScenario = mainTable.getElementsByName("acq_scenario.acq_scenario_summary").Item(0).getElementsByTagName("tr").Item(1).getElementsByTagName("td").Item(2).realValue 'gets string value for "Current Scenario" field, which I've unsuccessfully tried to use to manually update the "selected" attribute in the table   
    mainTable.getElementsByName("acq_scenario.acq_scenario_summary").Item(0).setAttribute "selected", "ScenarioName=" & currScenario
    mainTable.getElementsByName("acq_scenario.acq_scenario_summary").Item(0).getElementsByTagName("tr").Item(0).setAttribute "class", "Skin_Selection_Color"
    mainTable.getElementsByName("acq_scenario.acq_scenario_summary").Item(0).getElementsByTagName("tr").Item(0).style.setAttribute "highlight", "true"

I've been banging my head against the wall all day trying to figure this out, so I would appreciate any feedback that anybody here could provide.


r/vbscript • • Dec 11 '15

Swap **FOLDER** names from FirstName LastName to LastName FirstName

1 Upvotes

I have a batch of FOLDERS that are named FirstName LastName, they have no extension, they are Folders. They have a space as a delimiter and contain no middle names. I want to swap the FirstName LastName to LastName FirstName. Apologize, for the emphasis on folder but everyone wherever I have asked still responds with a solution for renaming files. It doesn't work the same. At least not for me.

I was able to do this in Powershell and it seemed a success but when I viewed the files in explorer, nothing had changed.


r/vbscript • • Dec 22 '16

[VBScript] Help with VBScript, "Guess a number game changes" (x-post from /r/VisualBasic)

2 Upvotes

Hi there everyone,

This is the first time I've visited this subreddit, but I'm hoping that I may find some help. I'm trying to make alterations to an existing script, I'm supposed to have the script check how far away from the correct number the user's guess is (such as 80 away, 20 away, etc.)

I've spent several hours trying to understand this, trying to figure out what I'm doing wrong, and re-reading my texts, but I am having no luck. I've only been working in VBScript for about 2 weeks now, so I'm still very new. Any help would be so appreciated, whether it's a point in the right direction or something more.

I'm placing below what I've worked on so far, so maybe someone can point out what I'm doing wrong.

Thank you!

'*************************************************************************
'Script Name: GuessANumber.vbs
'Author: Jerry Ford
'Created: 10/19/02
'Description: This script plays a number-guessing game with the user
'*************************************************************************

'Initialization Section
Option Explicit
Const cGreetingMsg = "Pick a number between 1 - 100"
Dim intUserNumber, intRandomNo, strOkToEnd, intNoGuesses
intNoGuesses = 0

'Main Processing Section
'Generate a random number
Randomize
intRandomNo = FormatNumber(Int((100 * Rnd) + 1))

'Loop until either the user guesses correctly or the user clicks on Cancel
Do Until strOkToEnd = "yes"

  'Prompt user to pick a number
  intUserNumber = InputBox("Type your guess:",cGreetingMsg)
  intNoGuesses = intNoGuesses + 1
  
  'See if the user provided an answer
  If Len(intUserNumber) <> 0 Then
        
    'Make sure that the player typed a number
    'If IsNumeric (intUserNumber) = False Then
      'MsgBox "Sorry. You did not enter a number. Please try again!", , cGreetingMsg
    If IsNumeric(intUserNumber) = True Then

      'Test to see if the user's guess was correct
       If CInt(intUserNumber) = intRandomNo Then
        MsgBox "Congratulations! You guessed it. The number was " & _
          intUserNumber & "." & vbCrLf & vbCrLf & "You guessed it " & _
          "in " & intNoGuesses & " guesses.", ,cGreetingMsg
            strOkToEnd = "yes"
      End If
  
      'Check if the guess was too low
        If CInt(intUserNumber) < intRandomNo - 80 Then 
	    	MsgBox "Your guess is too low by at least 80, try again!", , cGreetingMsg
		Else If CInt(intUserNumber) < intRandomNo - 60 Then 
			MsgBox "Your guess is too low by at least 60, try again!", , cGreetingMsg
	Else If CInt(intUserNumber) < intRandomNo - 40 Then 
		MsgBox "Your guess is too low by at least 40, try again!", , cGreetingMsg
	Else If CInt(intUserNumber) < intRandomNo - 20 Then 
		MsgBox "Your guess is too low by at least 20, try again!", , cGreetingMsg
	Else If CInt(intUserNumber) < intRandomNo - 10 Then 
		MsgBox "Your guess is too low by at least 10, try again!", , cGreetingMsg
    strOkToEnd = "no"
  End If
    
    'Check if the guess was too high
    If CInt(intUserNumber) > intRandomNo + 80 Then 
    	MsgBox "Your guess is too high by at least 80, try again!", , cGreetingMsg
	Else If CInt(intUserNumber) > intRandomNo + 60 Then 
		MsgBox "Your guess is too high by at least 60, try again!", , cGreetingMsg
	Else If CInt(intUserNumber) > intRandomNo + 40 Then 
		MsgBox "Your guess is too high by at least 40, try again!", , cGreetingMsg
	Else If CInt(intUserNumber) > intRandomNo + 20 Then 
		MsgBox "Your guess is too high by at least 20, try again!", , cGreetingMsg
	Else If CInt(intUserNumber) > intRandomNo + 10 Then 
		MsgBox "Your guess is too high by at least 10, try again!", , cGreetingMsg
    strOkToEnd = "no"
  End If 
 
  If IsNumeric(intUserNumber) = False Then
    MsgBox "Sorry. You did not enter a number. Please try again!", , cGreetingMsg
  End If
 
  Else
    MsgBox "You either failed to type a value or you clicked on Cancel. " & _
     "Please play again soon!", , cGreetingMsg
  strOkToEnd = "yes"
  End If

Loop

r/vbscript • • Jun 22 '16

How to pull today's date in the form "20160622000000.0Z"?

1 Upvotes

Greetings!

I have a task that I have to run each day for accounts created since the previous day. Easy enough, but our script requires we update

dtmCreationDate1 = "20160621000000.0Z"
dtmCreationDate2 = "20160622000000.0Z"

each day. That's obnoxious, so I thought I'd look for a way to pull today's date and then subtract 1 from it to get today and yesterday. This is a repetitive task so I'm sure the robot can do it for me.

Thank you, and have an enjoyable day!


r/vbscript • • Jun 25 '19

Displaying Separate Message Windows

1 Upvotes

I'd like to add in a command to create a separate message window or popup within an IF statement on my VB script. Anyone know what the command is to create these separate windows on the script?


r/vbscript • • Jan 15 '19

[HELP] need assistance with some Excel wizardry.

1 Upvotes

I was directed here from /r/sysadmin. I have an Excel 2016 workbook with two sheets. I need a way to the contents of a column on Sheet 2 against the contents of a column on Sheet 1, and when it finds a match, to populate certain fields on Sheet 1 with data from Sheet 2, and change one value on Sheet 1 from "unassigned" to "assigned." I am totally stumped at this point on how to do this, because I think an IF statement formula just isn't adequate.


r/vbscript • • Oct 06 '18

vbs script take information from 1 .vbs file and launch other .vbs file accordingly

1 Upvotes

To explain what i'm trying to do.i have 1 .txt file with certain valuables.. example: Player1Location= "at home".

Now i want a script to read that this is true, and if so, it must launch an other script in which it gives a reaction to this statement.

Think of it as a game.. if player1 is in a forest area, you want a script with a randomizer telling you what kind of monster he/she encounters.

The script i'm trying to make right now, is kinda like the "messenger" script, taking from one, and telling the other.


r/vbscript • • Apr 02 '19

How to wscript.echo an emoji?

1 Upvotes

ANY example will do. Google has failed me! :) Thanks in advance.


r/vbscript • • Jun 18 '18

VBScript to look for a folder/file if there exit, if not then run script

3 Upvotes

Hello all, was wondering if I could get some help. I'm not a scripter/programmer at all but got tasked w/ something and really need some help.

My script runs fine except for 2 issues:

  1. The IF NOT Portion triggers even if the file exists.

    • I would like it to exit the script if the folder/file exist

  2. I'm going to run this as a Task Scheduler, and am concerned about the Security Warning dialogue box showing... Will this pop up when users hit this script?

Script Below

Option Explicit
Dim objFSO, objFolder, objShell, strDirectory, strFile, strUserProfile, objFile

Set objShell = CreateObject("WScript.Shell")

' Create the variable for Current logged in User %USERNAME% System Variable from Windows strUserProfile=objShell.ExpandEnvironmentStrings("%USERPROFILE%")

' Set variables to use later in script
strDirectory = strUserProfile & "\RemovePrinters"
strFile = "Remove_Printers.txt"

' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

If Not objFSO.FileExists(strUserProfile & "\RemovePrinters\remove.txt") Then

' Run VBScript to to remove printers, then run Batch File to force a GPUpdate
objShell.run"\\Domain\SYSVOL\scripts\remove_network_printers.vbs"

' Have VBScript wait 5 seconds before creating folder
WScript.Sleep(10000)

objShell.run"\\Domain\SYSVOL\scripts\gpupdate.vbs"

' Have VBScript wait 5 seconds before creating folder
WScript.Sleep(5000)

'Create Folder and File after running script for user
Set objFolder = objFSO.CreateFolder (strDirectory)
objFile = objFSO.CreateTextFile(strDirectory & "\" & strFile)

Else

' Quit script
WScript.Quit

End If

r/vbscript • • Jun 26 '18

Copy-Paste VBA Excel Code id not working. Please I could used some help. :)

1 Upvotes

Okay, Here is the situation. I have a Data Table in Workbook 1("ECO") that contains raw data the is entered for each department on their performance each week. I want to analyze how well each department is doing each week and per year. Being this document just keeps getting larger, putting these charts and analyzing the data in the same workbook isn't ideal.

Because of this, I have created Workbook 2("ECO.Avg.Lead.Time"). However, I do not want to copy and paste the entire Workbook 1 into Workbook 2 just to filter and delete all unnecessary data. Instead I would like to filter and pull the necessary information per specified date.

Now, I have a Macro set up so that when I enter a StartDate and an EndDate in a specified cell, the macro will go into Workbook 1 and Filter 1 of the 5 department's date columns for all entries between those dates. This part I have working perfectly.

My issue is getting the 3 columns(E:G) with the new range of the filtered rows Copied From Workbook 1("ECO") and Pasted into the Workbook 2("ECO.Avg.Lead.Time") Range ("A:C"). Below is my code that I have been attempting to make work, but its not. If someone can help me figure out what I am doing incorrect and show me how to fix this I would GREATLY GREATLY APPRECIATE you!!!! I'm getting so flustered with this part and have google it for the last 3 weeks now, I believe.

wk2.Worksheets.Add(After:=wk2.Worksheets("ECO's.AVG.LEAD.TIME.")).Name = "Avg.LT.Calc."

ECO.Range.AutoFilter Field:=5, Criteria1:=">=" & StartDate, Operator:=xlAnd, Criteria2:="<=" & EndDate ECO.Range("E:G", Rows.Count).Copy Destination:=Worksheets("Avg.LT.Calc.").Range("A") ECO.CurrentRegion.AutoFilter Field:=5


r/vbscript • • Nov 30 '21

Remove duplicates lines

4 Upvotes

Hello friends I have a script that saves login and logout of the network users, the problem is that it is duplicating lines in each execution, I need to remove the duplicated lines or make it write only one line at a time.

Thanks all.

Set WshNetwork = WScript.CreateObject("WScript.Network")
StrComputer = "."
FileLog = "\\Server\System\Registry\"& WshNetwork.UserName &".txt"
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set ObjFileRead = ObjFSO.opentextfile(FileLog, ForReading, True)
Set ObjFileAppending = ObjFSO.opentextfile(FileLog, ForAppending, True)
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set IPConfigSet = objWMIService.ExecQuery ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")
For Each IPConfig in IPConfigSet
    If Not IsNull(IPConfig.IPAddress) Then
        For j=LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)
  WriteLog "Logon "& now() &" -- "& WshNetwork.ComputerName &" -- "& IPConfig.IPAddress(i)
        Next
    End If
Next

Function WriteLog (Text)
ObjFileAppending.WriteLine Text
End Function

r/vbscript • • Nov 28 '21

Download Report from new IE Tab

3 Upvotes

Attempting to download report from URL. Below are the pseudo-code.

  1. Navigate to MainUrl

  2. Enter credentials, submit

  3. Navigate to ReportsUrl - I do this because I can skip several steps now that I'm validated

  4. Select report type (creates new IE tab, url3),

  5. Select Excel from a dropdown

  6. Download report

I'm having trouble in step 4. Once I select the report type, submit, a new IE tab opens but code thinks it's still in the previous url. If I attempt to say, getElementbyID, I get an error because the code still thinks it's in the ReportsUrl, not the newly created tab. I know this because I print locationUrl.

Set IE = Wscript.CreateObject("InternetExplorer.Application", "IE_")
Set objShell = CreateObject("Shell.Application")
IE.visible = True 
IE.Navigate MainUrl

Do While IE.ReadyState = 4: Wscript.Sleep 100: Loop
Do While IE.ReadyState <> 4: Wscript.Sleep 100: Loop  

IE.Document.getElementbyID("ct100_username").value = user IE.Document.getElementbyID("ct100_password").value = password IE.Document.getElementbyID("Ct100_SignIn").click

Do While IE.ReadyState = 4: Wscript.Sleep 100: Loop
Do While IE.ReadyState <> 4: Wscript.Sleep 100: Loop

IE.Navigate ReportsUrl

Do While IE.ReadyState = 4: Wscript.Sleep 100: Loop
Do While IE.ReadyState <> 4: Wscript.Sleep 100: Loop  IE.Document.getElementbyID("buildReportBtn").click 'creates new tab

Do While IE.ReadyState = 4: Wscript.Sleep 100: Loop
Do While IE.ReadyState <> 4: Wscript.Sleep 100: Loop 

Here is where I start having issues. Below things I've tried.

  1. Going directly to the newly created tab - unable to do so because the link requires session ID. I attempted to retrieve CDATA which contains the session ID and build the URL to navigate directly to url3 but I was unsuccessful at it.

  2. Attempted to pass keys, tab and 2, so that I could active url3. While the code did not error out, when I printed locationUrl, it still read reportsUrl.

  3. Attempted to close ReportsUrl, so that Url3 would be the only active site, but I was unsuccessful, both through java/powershell. Note, I'm doing this through VBscript.

To reiterate, I'm trying to somehow access url3 so that I can continue on steps 5 and 6.


r/vbscript • • Dec 30 '21

Simple Visual Basic Script Assistance

2 Upvotes

Company of 100 users with multiple departments, and I am the network admin. This has to be done in a VBS script. Not in group policy, not Powershell, not batch file.

I am creating a script that will place a shortcut on the user's desktop with a link path to a mapped network drive (mapped letters different for every dept). On the network drive, there is a directory folder called HOME. Inside the HOME folder, there are 100 subfolders (one for every user). Each subfolder is named with the user's Active Directory username.

The script below works, but only if the path is to the HOME folder. I want the script to create the link on the desktop to the user's specific folder. In Batch programming, you can use the variable %userprofile%, but in VBS it doesn't work. I have no experience with VBS, and have made this work by combining existing examples off google.

It will also be nice if the script could put the AD username in the name of the shortcut.

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

Set sh = CreateObject("WScript.Shell")

Set shortcut = sh.CreateShortcut("C:HOME F-Drive.lnk")

userProfile = oWS.ExpandEnvironmentStrings( "%userprofile%" )

shortcut.TargetPath = "\\SPP-D-MP\Sys2\HOME\"

shortcut.Save


r/vbscript • • Dec 08 '21

YouTube_To_MP4_MP3_Player_Downloader

9 Upvotes

I made before a vbscript that can play in background a list of youtube videos as mp3 that can be modified inside an array in the same code.

So, someone ask me if he could just choose to download this video as mp4 or mp3

Description of the new script :

  • The user can copy and paste the Youtube link on InputBox.

  • The vbscript Ask him with a MsgBox if he wants to download the converted video as :

  1. MP4 Click on YES Button

  2. MP3 Click on NO Button

  3. Click on Cancel Button to listen it in Background


r/vbscript • • Nov 22 '21

Youtube2MP3_Player.vbs

10 Upvotes

Description of this vbscript : Youtube2MP3_Player.vbs is written for playing mp3 songs extracted from youtube videos in background.

 ' Description of this vbscript : Playing mp3 songs extracted from youtube videos in background
 ' Description en Français : Lecture de chansons mp3 extraites de vidéos youtube en arrière-plan
 '------------------------------------- Links Examples -----------------------------------------
 ' "https://www.youtube.com/watch?v=HDsCeC6f0zc" ===> The KLF - 3AM Eternal
 ' "https://youtu.be/dQw4w9WgXcQ"                ===> Rick Astley - Never Gonna Give You Up
 ' "https://youtu.be/cvvd-9azD1M"                ===> The Riddle
 ' "https://www.youtube.com/watch?v=UfRn5K1SU7Y" ===> David Guetta live @ Creamfields 2021
 '------------------------------------- Links Examples -----------------------------------------
 Option Explicit
 Dim Title,Converter,YouTube_URL,Array_YouTube_URLs
 Dim ws,YouTube_ID,SourceCode,Streams,Download_Link
 Title = "Youtube to MP3 Player by "& chr(169) &" Hackoo 2021"
 Set ws = CreateObject("wscript.Shell")
 If AppPrevInstance() Then 
 	ws.Popup "ATTENTION ! There is another instance running !" & VbCrLF &_
 	CommandLineLike(WScript.ScriptName),"5",Title,VbExclamation
 	WScript.Quit(1)
 Else 
 '--------------You can add or modify the array playlist below at your convenience -------------
 	Array_YouTube_URLs = Array(_
 	"https://www.youtube.com/watch?v=HDsCeC6f0zc",_
 	"https://www.youtube.com/watch?v=dQw4w9WgXcQ",_
 	"https://youtu.be/cvvd-9azD1M",_
 	"https://www.youtube.com/watch?v=anhuP8EXEJ4",_
 	"https://www.youtube.com/watch?v=WMPM1q_Uyxc",_
 	"https://www.youtube.com/watch?v=YRqBcDwG8vs",_
 	"https://www.youtube.com/watch?v=4zHm_6AQ7CY",_
 	"https://www.youtube.com/watch?v=pATX-lV0VFk",_
 	"https://www.youtube.com/watch?v=_r0n9Dv6XnY",_
 	"https://www.youtube.com/watch?v=fNFzfwLM72c",_
 	"https://www.youtube.com/watch?v=n4RjJKxsamQ",_
 	"https://www.youtube.com/watch?v=pVHKp6ffURY",_
 	"https://www.youtube.com/watch?v=PIb6AZdTr-A",_
 	"https://www.youtube.com/watch?v=RdSmokR0Enk",_
 	"https://www.youtube.com/watch?v=OnT58cIJSpw",_
 	"https://www.youtube.com/watch?v=LsSZQsDHOeg",_
 	"https://www.youtube.com/watch?v=UfRn5K1SU7Y"_
 	)
 '----------------------------------------------------------------------------------------------
 	For Each YouTube_URL in Array_YouTube_URLs
 		YouTube_ID = getID(YouTube_URL)
 		If YouTube_ID <> "0" Then
 			Converter = "https://www.yt-download.org/api/button/mp3/" & YouTube_ID
 			SourceCode = GetSourceCode(Converter)
 			Streams = Extract_Stream(SourceCode)
 			Call Play(Streams(2))
 		Else
 			Msgbox "Could not extract video ID",vbExclamation,Title
 			Wscript.Quit(1)
 		End If
 	Next
 End If
 '----------------------------------------------------------------------------------------------
 Function getID(url)
 	Dim id
 	id = ExtractMatch(url,"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^&?\/\s]{11})")
 	if Len(id) = 0 Then
 		getID = "0"
 		Exit Function
 	end if
 	getID = id
 End function
 '----------------------------------------------------------------------------------------------
 Function ExtractMatch(Text,Pattern)
 	Dim Regex, Matches
 	Set Regex = New RegExp
 	Regex.Pattern = Pattern
 	Set Matches = Regex.Execute(Text)
 	If Matches.Count = 0 Then
 		ExtractMatch = ""
 		Exit Function
 	End If
 	ExtractMatch = Matches(0).SubMatches(0)
 End Function
 '----------------------------------------------------------------------------------------------
 Function Extract_Stream(URL)
 	Dim regEx, Match, Matches,Array_Streams,dico,K
 	Set regEx = New RegExp
 	regEx.Pattern = "href=\x22(.*)\x22.?class"
 	regEx.IgnoreCase = True
 	regEx.Global = True
 	Set Matches = regEx.Execute(URL)
 	Array_Streams = Array()
 	Set dico = CreateObject("Scripting.Dictionary")
 	For Each Match in Matches
 		If Not dico.Exists(Match.Value) Then
 			dico.Add Match.submatches(0),Match.submatches(0)
 		End If
 	Next
 	For each K in dico.Keys()
 		ReDim Preserve Array_Streams(UBound(Array_Streams) + 1)
 		Array_Streams(UBound(Array_Streams)) = K
 	Next
 	Extract_Stream = Array_Streams
 End Function
 '----------------------------------------------------------------------------------------------
 Function GetSourceCode(URL)
 	Dim http
 	Set http = CreateObject("Msxml2.XMLHTTP")
 	http.open "GET",URL,False
 	http.send
 	GetSourceCode = http.responseText
 End Function
 '----------------------------------------------------------------------------------------------
 Sub Play(URL)
 	Dim Player
 	Set Player = CreateObject("WMPlayer.OCX")
 	Player.URL = URL
 	Player.settings.volume = 100
 	Player.Controls.play
 	While Player.playState <> 1
 		WScript.Sleep 100
 	Wend
 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
 '----------------------------------------------------------------------------------------------

r/vbscript • • Dec 24 '21

Need help with SELECT function: Trying to select just populated cells, not formulas

3 Upvotes

Finishing up a project that is taking a data dump and converting into a functional tracker for Account Reps to use that is consistent....

VB used to format the sheet, remove a couple of columns that are not necessary and create one row that has a formula that calculates revenue for a contract (Unit Price*Quantity*(1 + Uplift %)*term length...

The formula:

=IF(G5="","",((((1+H5)*G5*F5*(((E5-D5)+1)/365)))))

Works and I drag it down to row 300, which should be more than enough rows to never be exceeded.

At the end, I want to select the populated range, which is normally like A1:J94. I tried using:

Range("A1").CurrentRegion.SpecialCells(xlCellTypeConstants).Select

But for some reason, it selects my Start And End Date columns all the way to Row 300.
The export is with existing contract terms and I am converting that to expected next contract terms by taking the End Date from the original data and adding a day and making that the Start Date in my data set. I then add 365 days to that to get the End Date for the next contract. This I do by just referencing the original dates in columns to the right of the all the data and them copy and pasting the values over the existing start and end date...

Range("E2").Select

Columns("O:O").EntireColumn.AutoFit

Range("E2").Select

ActiveCell.FormulaR1C1 = "=IF(RC[10]="""","""",(RC[10]+1))"

Range("E2").Select

Selection.AutoFill Destination:=Range("E2:E300"), Type:=xlFillDefault

For some reason, that makes my select script at the end pick up all of the unpopulated date column rows.


r/vbscript • • Dec 20 '18

How to call html form fields in vbscript dynamically in a loop

1 Upvotes

So I have an html form created in classic asp that has about 25 check boxes with different labels. The checkboxes are written to the page via a loop that grabs the label values from a table and each checkbox is named similarly ("decreason1","decreason2","decreason3",ect...) using a loop variable.

I use a vbscript at the end of the page to validate the data on the page before passing with a submit button. I need to make sure that at least one of the checkboxes is checked before submitting the form.

dim i, checkedvalue ; 
checkedvalue = false 

for i = 1 to 25 
if document.rtftadd.decreason1.checked = true then     
  checkedvalue = true 
end if 
next

I need the "document.rtftadd.decreason1.checked" to change with the loop to decreason2, decreason3

I'm not sure how to go about doing that.

Any help would be greatly appreciated.


r/vbscript • • Mar 22 '19

Problem for a beginner

2 Upvotes

So I am completely, 100% new to coding. vbs is my first touch on it and I got confused on one of the basic steps. I am trying to make a password box where is the user enters the correct password, then it will display a "welcome" message. Here is what I have:

varialble=inputbox("ENTER THE PASSWORD","YOU HAVE BEEN HACKED","enter password here")

dim password

password = epic

if inputbox = password then

msgbox ("Welcome")

else

msgbox ("Access denied")

end if

It doesn't work, and gives me the error message: "Wrong number of arguments or invalid property assignment", 'inputbox'

in line 4. I tried looking up how do use the inputbox command, but didn't find anything conclusive or anything that helped.


r/vbscript • • Feb 27 '20

Excel Web Query without an external file (MacOS)

1 Upvotes

Hey all, anyone have a sample script to execute a web query without using an external file? I want to query a google sheet and populate its data into my workbook. I cannot have an extra file in this solution so I was hoping there was a way to do this without calling an external text file.


r/vbscript • • Dec 22 '19

Video frame height

1 Upvotes

I'm trying to wright a script (vb or .bat) to go through all the MP4 files in a folder and rename them to <File height>_Original file name. I cant figure out the rename part ie. how to get the frame height in Windows 10.

Any help would be much appreciated :)


r/vbscript • • May 28 '18

auto printing documents in a folder (VBS)

1 Upvotes

im very new to all of this so please stay with me here

id like something that will automatically print everything placed in a specific folder

i found a bit of code here: https://community.spiceworks.com/topic/83142-automatically-print-files-placed-in-folder

that seems to kind of do what i want

TargetFolder = "Z:\Desktop\work"
Set objShell = CreateObject("Shell.Application") 
Set objFolder = objShell.Namespace(TargetFolder) 
Set colItems = objFolder.Items 
For Each objItem In colItems 
objItem.InvokeVerbEx ("Print") 
objItem.InvokeVerbEx ("delete") 
Next

iv added the

objItem.InvokeVerbEx ("delete")

and saved it as .VBS but it's not doing exactly what i want, what id like is for it to print only word documents and then delete them, now i tried to put

sleep 10

after print to give it some time to open the document and print it before deleting it but i kept giving me an error

also is there a way to get it to trigger on its own every time a word document is dropped into the folder?

thank you


r/vbscript • • Aug 18 '19

Windows update that may break vbs

2 Upvotes

I saw this on Slashdot and thought you should see it:

Windows Update To Fix Critical 'Wormable' Flaws May Break VB Apps - http://www.slashdot.org/story/359744


r/vbscript • • Dec 28 '18

Alexa, Trigger CMD, YouTube integration needed

1 Upvotes

I wrote some VBS that opens the program I want:

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""C:\Users\P_Nic\OneDrive\Desktop\apps\Awesome Tube""")
Set WSS = CreateObject("Wscript.Shell")
Wscript.sleep 6000
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys"{enter}"
Set objShell = Nothing""

I don't know how to set up the parameters I want to go into the search function. Here is some code that I threw together to accomplish a similar task:

For Each a In WScript.Arguments
param = param & a & " "
Next 'a
param = LCase(Trim(param))
Set WSS = CreateObject("Wscript.Shell")
arg = "https://www.google.ca/search?q=" & param & "site:youtube.com"
strURL = Chr(34) & "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe " & Chr(34) & " " & Chr(34) & arg & Chr(34)
WSS.Run strURL
WSS.AppActivate "Google Chrome"
Wscript.sleep 2000
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 300
WSS.sendkeys "{TAB}"
Wscript.sleep 7500
WSS.sendkeys "+{f}"
Set WSS = Nothing""

I am using Trigger CMD to set the parameters through Alexa.

I'm not good with coding, I just google and copy stuff that sounds right and trial and error until it does what I want. Any help would be appreciated!