VB Script





VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic, but with some important differences. VBScript is commonly used for automating administrative and other tasks in Windows operating systems (by means of the Windows Script Host) and for server-side scripting in ASP web applications. It is also used for client-side scripting in Internet Explorer, specifically in intranet web applications.

Share tech news, updates, or what's on your mind.

Sign up to Post


Need help in how to do a vbs file for doing the below procedure:

Fixing DameWare to run on Windows10
            a. Copy file from //myDomain/Support/DameWare/dwdrvinst64.exe to c:/MyLogFile/
            b. Run CMD as Administrator
            c. cd ..
            d. cd /MyLogFile
            e. dwdrvinst64 -remove smartcard
            f. dwdrvinst64 -install smartcard

Don't know of a better way, or even run an *exe to do this...

Please help.

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Can you please help with a batch or VB Script,
I need to remove from all file names in a a folder (with sub Folders)


Should be

Your help is greatly appreciated.

I use a customized Outlook form that runs VB Script.  I have a command button that opens up a Word template and prints it to a PDF file.  What happens though is when printing, the save PDF dialog box comes up.  I don't want that.  I want it to save it as a PDF automatically without the dialog box coming up.  Let's just say C:\test.pdf.  Here's the code that I currently use.

Sub CommandButtonShipLabelUSPS_Click()

On Error Resume Next

Dim strCurrentPrinter' As String

      Set objDoc2 = GetWordDocLabel("\\TGPS13VM1\drawing$\Jobs\Task_Templates\Ship-Ship Label USPS.dot")
          Call FillFieldsShipLabel(objDoc2)
          objDoc2.Application.Options.PrintBackground = False
          objDoc2.Application.DisplayAlerts = False

if Item.UserProperties("PrintHold") = True then
        Set objDoc2 = Nothing
        Set strCurrentPrinter = Nothing
        Set objWord2 = Nothing
      Exit Sub
end if

          strCurrentPrinter = objDoc2.Application.ActivePrinter ' store the current active printer
          objDoc2.Application.ActivePrinter = "Adobe PDF" ' change to another printer

          objDoc2.PrintOut ' print the active sheet
      Call RestoreActivePrinter

      objDoc2.Application.DisplayAlerts = True
          objDoc2.Application.Options.PrintBackground = True

objDoc2.Close wdDoNotSaveChanges
objWord2.Quit wdDoNotSaveChanges

      Set objDoc2 = Nothing
        Set strCurrentPrinter = Nothing
        Set objWord2 = Nothing

End Sub

Thank you,
having used the same code for various functions which worked well.. I added an extra column "Q" but now I keep getting the runtime error and I'm not sure why...

ive attached a sample copy of the table and the code (highlighted).. as I say everything was working well until I added the extra column and additional filter
My previous application in VB6 would create a record using the code below:


Module basDeclarations

Public Const maxTables = 20

Structure Gametype
    <VBFixedString(6)> Public memberID As String
    Public TableID As Integer
    Public StartTime As Date
    <VBFixedString(1)> Public Occupied As String
End Structure

End Module


Public Sub CreateCurrentGamesFile()
    Dim OneGame As Gametype
    Dim TableNumber As Integer
    Open app.path & "\CurrentGames.dat" For Random As #1 Len = Len(OneGame)
    For TableNumber = 1 To maxTables
        OneGame.memberID = ""
        OneGame.TableID = TableNumber
        OneGame.Occupied = "N"
        Put #1, TableNumber, OneGame
    Next TableNumber
    Close #1
End Sub
End Class

How can I convert this block of code in vb.net to create new records as a random access file? Or Is there a better way to store records which can be easily saved and deleted in vb.net? Thanks

Please provide comments on your code
I am trying to paste excel sheet table in oulook body but i am getting error.
Runtime error 91Object varialbe or with block variable not set.

below are the code

Sub CreateMail()
Dim objOutlook As Object

Dim objMail As Object

Dim rngTo As Range

Dim rngSub As Range

'Dim rngMessage As Range

Dim rngCc As Range
Dim RngCopied As Range

Set objOutlook = CreateObject("Outlook.Application")

Set objMail = objOutlook.CreateItem(0)

With ActiveSheet

Set rngTo = .Range("B1")

Set rngCc = .Range("B2")

Set rngSub = .Range("B3")

'Set rngMessage = RangetoHTML(RngCopied)


End With

With objMail

.To = rngTo.Value

.Cc = rngCc.Value

.Subject = rngSub.Value

.Body = RangetoHTML(RngCopied)

.Display 'Instead of .Display, you can use .Send to send the email _

End With

On Error GoTo 0

Set objOutlook = Nothing

Set objMail = Nothing

Set rngTo = Nothing

Set rngCc = Nothing

Set rngSub = Nothing

'Set rngMessage = Nothing

'Set RngCopied = Nothing

End Sub

Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2010
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook
    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
    'Copy the range and create a new workbook to past the data in
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8

Open in new window

I'm writing a vbscript wherein auotamically create a folder that rename as date/time stamp. I create vbscript wherein the telnet output file save as .text then save on the folder that automatically created. This is my script on the telnet output file.

Option Explicit

On Error Resume Next

Dim WshShell

set WshShell=CreateObject("WScript.Shell")

WshShell.run "cmd.exe"

WScript.Sleep 1000

'Send commands to the window as needed - IP and commands need to be customized

'Step 1 - Telnet to remote IP'

WshShell.SendKeys " -f C:\log.txt"
WshShell.SendKeys ("{Enter}")
WScript.Sleep 1000

'Step 2 - Issue Commands with pauses'

WshShell.SendKeys ("password")

WScript.Sleep 1000

WshShell.SendKeys ("{Enter}")

WScript.Sleep 500
WshShell.SendKeys ("Enable")
WshShell.SendKeys ("{Enter}")
WScript.Sleep 500

WshShell.SendKeys ("password")
WshShell.SendKeys ("{Enter}")
WScript.Sleep 500

WshShell.SendKeys ("terminal length 0")
WshShell.SendKeys ("{Enter}")
WScript.Sleep 500

WshShell.SendKeys ("show mac address-table vlan 13")
WshShell.SendKeys ("{Enter}")
WScript.Sleep 1000

WshShell.SendKeys "exit"
WshShell.SendKeys ("{Enter}")
WScript.Sleep 500

WshShell.SendKeys ("{Enter}")
WScript.Sleep 500

Open in new window

I have a lot of rows of data and what I'm looking for is on columns G and H I wanted to highlight the entire row red (bad) if the date on Column H is greater than the date on Column G  AND only those red ones imported to a sheet called PASS_DUE_REPORT.

See attachment for what it should look like.  Thank you.....
Hi Experts, I have two tables named, Invoices and Establishment. I'm using codes below to obtain the data but unfortunately the codes is not working. How to correct the codes? Thank you!

Set rs = cn.Execute("Select i.INVOICENO, i.DATEPURCHASE, i.EncodedBy from Invoices i inner join Supplier s on i.VNDRID=s.Establishment")

Open in new window

Hi experts, How to correct codes below where I need to access the datetime fields, TheDate. Codes below is not working. Any help please!

Set rs = cn.Execute("Select Proname from Stock where TheDate Between '" & sdate & "' And '" & edate & "' And PROCODE='" & code & "' Order by icount")

Open in new window

On Demand Webinar - Networking for the Cloud Era
On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Hi Experts, I'm using the code below to print data in div. However, I noticed that the approached would open other window and that be able to show other page to print or to save. My problem is that I could no longer run my web site once this window will not close. This Untitled page would stop me from re-running my site. Is there anyone who can explain me why this thing is happen? What's the solution to prevent this problem? Thanks!

function printData(id){
   var divToPrint = document.getElementById('Prolist-A34');
   newWin= window.open();

Open in new window

I am working on a generic VB ASP page for all our sites that will toss up the status code and error message, works great in testing directly to it or redirecting to it...however if I leverage the page as a file, it doesnt execute any of the asp vb code

I wrote it generically so that it could be placed on any of our corporate sites and offer redirection to that applications home root or our corp status page...it uses the following in the code

Code snips

      <meta http-equiv="refresh" content="500;url=https://<%Response.Write(Request.ServerVariables("SERVER_NAME"))%>"/>

      Dim StatusCode
      Dim StatusMessage
      StatusCode=split(response.status," ")(0)
      <h1 style="font-size: 170px;"><%Response.Write(StatusCode)%></h1>
    <p style="width: 400px; margin-left: auto; margin-right: auto; margin-top: 15px;">
        Sorry, but the page you are looking for has not been found. Try checking the URL for an error, then hit the refresh button on your browser. Click the button below to navigate to the <%Response.Write(Request.ServerVariables("SERVER_NAME"))%>:    
    <a class="btn btn-primary m-t" href="https://<%Response.Write(Request.ServerVariables("SERVER_NAME"))%>">Home</a>
      <p> Error Code: <%Response.Write(Response.Status)%></P>
It is available here: https://exchange.nagios.org/directory/Addons/Monitoring-Agents/DFS-Replication-and-BackLog/details

I am trying to set this up in my environment so I can track dfsr without having to manually check it.
However, when I try running it on Nagios I get the error:
DFS-Backlog.vbs(7, 1) Microsoft VBScript runtime error: Subscript out of range

I searched around and the best hint to the solution I could find is other VBscripts that monitor DFS have this error when the Replicated Groups and/or Folders have spaces in the name.
Both have spaces in my DFSR setup.

I think if a change is made to accommodate spaces in Replicated Groups/Folders names - then this script will work. Would someone be able to point out what line needs to be changed and what it should be changed to?

strComputer = "." 
const intOK = 0
const intWarning = 1	
const intCritical = 2
const intUnknown = 3	
GroupName = Replace(WScript.Arguments.Item(0),"_"," ")
Warn = CInt(WScript.Arguments.Item(1))
Crit = CInt(WScript.Arguments.Item(2))
sTarget = "localhost"
set oPing = _
GetObject("winmgmts:{impersonationLevel=impersonate}"). _
ExecQuery ("select * from Win32_PingStatus where address = '" _
& sTarget & "'")

For Each o In oPing
  sResp = o.StatusCode : exit for

if sResp = 0 Then

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\MicrosoftDfs") 
Set colItems = objWMIService.ExecQuery( _

Open in new window

So when running this application there is some inline VB code:
<td><asp:Label ID="lblStartTime" runat="server" Text='<%# Convert.ToDateTime(Eval("StartTime")).ToString("hh:mm tt") %>' /></td>

Open in new window

This is where it is crashing and I cannot seem to find out why. The StartTime has a value until it gets to this point and I am getting invalid DateTIme string because the string is empty "". I am out of options and have done a lot of debugging with break points etc.  Then there is a corresponding piece of code:
cb.StartTime = IIf(dr("StartTime") Is DBNull.Value, "", dr("StartTime"))

Open in new window

and for some reason entries from the textboxes are not being pushed to the DB and are set to NULL.
I have text files that are exported every time we save a report from one of our programs. I am trying to compile a data table that is built from specific text from these text files. The text file is delimited with an = and the first column contains variable names and they are consistent across all of the text files i would like to import. The second column contains the text that I would like to be imported. My data table headers can be the same as the variable names in the text file, I imagine that could simplify importing the data properly. I attached a sample text file, I am not concerned about the values that are below [Test Raw Data], just the entries that are delimited by an =. I also attached a xlsm with the headers I am most concerned with [i would prefer if i could have them in any order and the macro would still work]. I would like to be able browse to select the file to import, and then have the desired text import to the next open row of the worksheet. The column headers will always be in the same row[ ex. row 4], but not in the same order as the text/xlsm file lists them.
Can a button activated macro be created for something like this? I could live with just importing one file and then copying that data to a different table, and repeating if needed.
Thank you.
Imports System.Data.OleDb

Public Class Reports
    Dim myDA As OleDbDataAdapter
    Dim myDataSet As DataSet

    Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles txbdat.TextChanged

    End Sub
    Public Sub DatagridData()
        Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Lenovo\Desktop\SAD\SadDatabase.accdb")
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Room1Report", con)
        myDA = New OleDbDataAdapter(cmd)

        Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(myDA)
        myDataSet = New DataSet()
        myDA.Fill(myDataSet, "Room1Report")
        Dgvrep.DataSource = myDataSet.Tables("Room1Report").DefaultView
        con = Nothing
    End Sub
    Public Sub DatagridGetData()
        Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Lenovo\Desktop\SAD\SadDatabase.accdb")
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [RegisteredSA] WHERE [IDnumber] = '" & Login.txbidn.Text & "' AND [Password] = '" & Login.txbpas.Text & "'", con)
        Dim reader As OleDb.OleDbDataReader = cmd.ExecuteReader()
        If reader.Read = True Then
            txbfir.Text = reader.Item("Firstname")
            txblas.Text = reader.Item("Lastname")

        End If
    End Sub
    Private …
So I have this script, but when I run it, it's not working, it doesn't delete the files.
So I had someone write this for me, and it's supposed to keep 150 files, and delete the files from the directory listed, and delete all etl files. Am I missing something?

@echo off (need to change the below to the locations needed and file types)

call :delolder 150 "E:\ms\Output_On_08-10-2017__Time_17-12-31PM" "etl"
exit /b

set type=%~3
set thedir=%~2
set keep=%~1
for /f "delims=" %%D in ('dir "%thedir%" /ad /b /s') do (
  echo Working on dir %%~fD
  for /F "skip=%keep% delims=" %%a in ('dir "%%~fD\*.%type%" /a-d /o-d /b 2^>NUL') do DEL "%%~D\%%~a"
echo Working on root dir %thedir%
for /F "skip=%keep% tokens=* delims=" %%a in ('dir "%thedir%\*.%type%" /a-d /o-d /b 2^>NUL') do if "%%~nxa" NEQ "%~nx0" DEL "%thedir%\%%~a"
exit /b

Open in new window


I tried saving a global.asa in the root of the webserver folder:
Sub Application_OnStart
    Dim cnnDem, cnnString
    Set cnnDem = Server.CreateObject("ADODB.Connection")
    cnnDem.CommandTimeout = 60
    cnnString = "Driver={SQL Server};Server=servername\SQLEXPRESS;Database=mcd;Uid=username;Pwd=password"
    Call cnnDem.Open(cnnString)
End Sub

Open in new window

Of course I replaced servername, username and password with the real values. But then no page on my website will show up. I just get the Server 500 error. If I move the global.asa away from the root, then the webfiles works again. What am I doing wrong? And how should I handle the global.asa file correctly to have sql server connection available in my web application?

Best regards

I am just starting to learn VBA so bear with me if  I keep asking for help
What I want here is to get the range of the column and highlight the column range
Private Sub OptColumns_Click()
Dim LastRow
LastRow = ActiveSheet.UsedRange.Rows.Count
    Application.ScreenUpdating = False
    With ActiveCell
        If (ActiveCell.Column >= 1 And ActiveCell.Column <= 2) And (ActiveCell.Row >= 6 And ActiveCell.Row <= LastRow) Then
          MsgBox ("Cannot Mark This Area")
             Dim a
                   'I want to highlight from row number 7 up to the last row
             Set a = Cells(7, LastRow)
             a.Interior.Color = RGB(255, 255, 0)
        End If
    End With
  Application.ScreenUpdating = True
End Sub

The expected result should be like this
In addition to my question
How can I highlight sheet form range ("C6") up to the last row
Dim LastRow
LastRow = ActiveSheet.UsedRange.Rows.Count
    Dim x As Range
    Set x = Worksheets("Product").Range("C6:KHL50").Cells
    Dim sRange As Range
    Set sRange = Range("A6:B100")
    Application.ScreenUpdating = False
    With ActiveCell
        If InRange(ActiveCell, sRange) Then
          MsgBox ("Cannot Mark This Area")
        ' Highlight the entire sheets up to the last row
          x.Interior.Color = RGB(255, 255, 0)
          sRange.Interior.ColorIndex = xlNone
       End If
    End With
  Application.ScreenUpdating = True

Enroll in August's Course of the Month
Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

I am creating a string using vb script and writing this string to a file. The problem is that the string contains 5 lines but when i write it into text file(notepad++) it writes these 5 lines and includes one extra 'crlf' by default! AS a result the file will have 6 lines (5 lines from string and 1 extra line -which i dont know how it is coming?)
I wrote the data into the file,closed it and then again opened it to remove that extra line!it was removed but i want it to be removed without opening the file again.
What is the VB script to copy data from one database/table and paste to another database/table?
How do you write a SQL Statement/Query on an SQL Server,that will look for the "PrintEvent" from a label application like Easy Label, Bartender, etc, and copy the data from the fields that were printed and then write that data to the Database?
I have a Macro Enabled Excel Sheet setup to retrieve API data from Goformz but For some reason when it get's to a record that has a blank latitude and longitude the script stops and doesn't retrieve any more records.

Question 1:  What do i need to add to the "latitude" and "location" code so if the record is blank add the word "NA" to the cell and continue running macro for remaining records??

Question 2: What do i need to add to the "lastupdatedate" code so the date format looks like this "dd/mm/yyy 00:00" and not
2017-08-09T01:36:39.0000000+00:00 ??

Question 3: When the tablestyle is applied it is applying it to the entire columns, instead of just only the columns that contain data. What do i need to change in my tablestyle code ??

TableStyle Code looks like this:

Dim rList As Range

On Error Resume Next
With Worksheets("Completed Forms")
    If .ListObjects.Count > 0 Then
        .ListObjects ("Table3")
        Set rList = .Range
    End If
End With

Sheets("Completed Forms").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:G:G"), , xlYes).Name = _
    ActiveSheet.ListObjects("Table3").TableStyle = "TableStyleMedium2"

Open in new window

Getting the Data from Goformz Code looks like this:

Sheets("Completed Forms").Cells.Clear
Dim http As Object,

Open in new window

Hi all,

I created a macro script for AS400, basically with the comand "autECLSession.autECLPS.SendKeys "word" / "right" / etc...

This macro script runs at perfection but the error comes when there is a variance in the screen, because sometimes depending of the value introduced, it jumps a box with information (that I have to introduce Y/N (yes/no)), or just, sometimes, the values introduced are incorrected (because exceed the limit of characters available for a string), and the macro starts to fall and collapse the console.

My question is the following: there is any method that when occur an error in the macro, and appears the X in the status bar, the macro stops at that point?)

Kindest regards.
I had this question after viewing Script to import contacts from Excel to Outlook.

with this script is it possible to copy contact to different folder in My Contacts?

VB Script





VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic, but with some important differences. VBScript is commonly used for automating administrative and other tasks in Windows operating systems (by means of the Windows Script Host) and for server-side scripting in ASP web applications. It is also used for client-side scripting in Internet Explorer, specifically in intranet web applications.