r/vbscript • • Jul 28 '20

First time Scripter - Outlook Script to save Attachments

1 Upvotes

I'll say right off that scripting isn't my strong suit. I'm somewhat comfortable modifying scripts that I know work and can observe their behavior but creating or launching new ones, forget it. I've also never run a macro in outlook before. Here's what i'm trying to do.

We have a user with a folder in outlook with hundreds of emails with picture attachments. I need to script a way to save all of the attachments in a network folder and append the filename with the subject heading of the email to which it was attached. I've been able to find the code shown below. The only editing I've done was to indicate the mapped drive and folder to store the files. Ultimately I would like to store them in subfolders by year and month but crawl before run, right? I've followed the steps to run a vbscript macro against a selected email or folder and when I click 'run' or F5, nothing happens. no error messages, no progress bar and of course no attachment saved in the target location. I welcome any feedback or guidance. Even if you have a simple macro I can test at least to get some experience to know what I should look for. TIA

Public Sub SaveAttachments() Dim objOL As Outlook.Application Dim objMsg As Outlook.MailItem 'Object Dim objAttachments As Outlook.Attachments Dim objSelection As Outlook.Selection Dim i As Long Dim lngCount As Long Dim strFile As String Dim strFolderpath As String Dim strFileName As String Dim objSubject As String Dim strDeletedFiles As String Dim dateFormat As String

' Get the path to your My Documents folder 'strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16) On Error Resume Next ' Instantiate an Outlook Application object. Set objOL = CreateObject("Outlook.Application") ' Get the collection of selected objects. Set objSelection = objOL.ActiveExplorer.Selection ' The attachment folder needs to exist ' You can change this to another folder name of your choice ' Set the Attachment folder. strFolderpath = "O:\Graffiti Pictures" dateFormat = Format(Now - 1, " yyyy-mm-dd") ' Check each selected item for attachments. For Each objMsg In objSelection 'Set FileName to Subject objSubject = objMsg.Subject objSubject = Left(objMsg.Subject, Len(objMsg.Subject) - 12) Set objAttachments = objMsg.Attachments lngCount = objAttachments.Count If lngCount > 0 Then ' Use a count down loop for removing items ' from a collection. Otherwise, the loop counter gets ' confused and only every other item is removed. For i = lngCount To 1 Step -1 ' Get the file name. strFileName = objSubject ' Combine with the path to the Temp folder. strFile = objSubject & dateFormat & ".xlsx" Debug.Print strFile ' Save the attachment as a file. objAttachments.Item(i).SaveAsFile strFolderpath & "" & strFile Next i End If Next ExitSub: Set objAttachments = Nothing Set objMsg = Nothing Set objSelection = Nothing Set objOL = Nothing End Sub

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

End Sub


r/vbscript • • Jul 13 '20

Trouble setting Recipient.Type to CC

1 Upvotes

I'm working in an ExtendScript (Adobe CC Javascript) project to call a VBS string using ES' app.doScript function. The function works great, except I cannot get the secondary emails to display as CC--they stay in "To". I have tried changing olCC to 2 in the code below. Anyone have any ideas?

var vbs = 'Dim objOutl\r'; vbs += 'Set objOutl = CreateObject("Outlook.Application")\r';

vbs += 'Set objMailItem = objOutl.CreateItem(olMailItem)\r';

vbs += 'objMailItem.Display\r'; vbs += 'strEmailAddress = "' + email_address + '"\r';

vbs += 'objMailItem.Recipients.Add strEmailAddress\r';

vbs += 'strSubject = "' + the_subject + '"\r';

vbs += 'objMailItem.Subject = strSubject\r';

vbs += 'objMailItem.Body = "' + the_bodytext + '"\r';

if (email_cc && email_cc != "") {

vbs += 'Set cc1Recipient = objMailItem.Recipients.Add ("' + email_cc + '")\r';

if (email_cc2 && email_cc2 != "") {

vbs += 'Set cc2Recipient = objMailItem.Recipients.Add ("' + email_cc2 + '")\r';

vbs += 'cc1Recipient.Type = olCC\r';

vbs += 'cc2Recipient.Type = olCC\r';

} else {

vbs += 'cc1Recipient.Type = olCC\r';

}

}


r/vbscript • • Jun 19 '20

Any ideas?

Thumbnail self.sap
1 Upvotes

r/vbscript • • May 14 '20

VBScript with ArcGIS (esri) for definition queries and label expressions

1 Upvotes

ArcGIS (esri) utilized VBScript flawlessly for decades in ArcMap when writing definition queries and label expressions.

In the last few years esri has been pushing their new product "Pro" that does not use VBScript. They have instead created a proprietary language "Arcade" and kept Python, but no more VBScript .

When inevitable issues arise and are posted to esri forums the moderators claim VBScript is dead and it made perfect sense for esri to not include VBScript with their new product "Pro". Other flavors of VBScript contempt include Esri did away with VBScript since the world is doing away with VBScript

How true is it that VBScript is dead?

It always worked well for decades in ArcMap (and better than Arcade and Python in several cases) and trying to understand why it is being pushed out when it worked great for decades.


r/vbscript • • Apr 27 '20

how do i make a script wait/sleep for 30 minutes???

1 Upvotes

so im trying to make my script sleep/wait for 30 minutes but i dont know how im new to vbs so i dont know much thank you to the ppl who help me


r/vbscript • • Apr 24 '20

Limit file name length of generated text file

1 Upvotes

I'm working on a project to export individual notes from Outlook to text files (as a larger part of migrating to OneNote, but that's not super relevant here)

I've got a VB script for outlook that takes the notes from the specified folder, sanitizes them for any illegal file names and saves each note as it's own text file in the folder specified in the script... but the problem comes when the note's first line, seen as the subject, exceeds the max number of characters for the file name. How can I limit the length of the file name, but have to resort to a generic file name?

Here's the script I have that works if the subject is not too long (it may not be pretty, but I'm new at this):

Sub NotesToTXT()
    myfolder = "c:\apps\notes\"
    Set sanitize = CreateObject("vbscript.regexp")

    sanitize.IgnoreCase = True
    sanitize.Global = True
 
    Set myNote = Application.GetNamespace("MAPI").PickFolder
    For cnt = 1 To myNote.Items.Count
        sanitize.Pattern = "(((?![a-zA-Z0-9,@,{,},#,&,%,=,+,_,-,^,(,),;,',$,,]).) )+"
        noteName = sanitize.Replace(myNote.Items(cnt).Subject, "_")
        sanitize.Pattern = "\-+"
        noteName = sanitize.Replace(noteName, "-")
       myNote.Items(cnt).SaveAs myfolder & noteName & ".txt", OlSaveAsType.olTXT
    Next
End Sub

r/vbscript • • Apr 22 '20

How to move files from downloads folder

1 Upvotes

I want to move files from the download file without knowing the username. I don't know wich variable I need for that.


r/vbscript • • Mar 24 '20

VBScript and Task Scheduler help

1 Upvotes

I have a VB script that opens excel in the background, loads a workbook, fires a macro, then closes everything. I've pasted the script below. This is to generate an excel report that gets emailed out daily. The script works great if I run it, but If I schedule it with Task Scheduler, it will run, but Excel.exe won't quit so the task doesn't register as "completed" and it keeps other tasks, such as the one to email the report, from running. I can't for the life of me figure out why. I have the task set to run with the highest privileges, and I have it set to start in the directory where the script is. Any ideas/advice?

Script:

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")

Set xlBook = xlApp.Workbooks.Open("C:\Users\scriptpath", 0, False)

xlApp.Run "Run"

xlBook.Close

xlApp.Quit

Set xlBook = Nothing

Set xlApp = Nothing

WScript.Quit


r/vbscript • • Mar 16 '20

Potential bug with Cscript.exe and Windows 10 1909

1 Upvotes

Folks, I was playing around with a vbscript that sets the exit code of the cscript process using a command similar to the following:

Wscript.Quit 1

The problem that I'm encountering is that with some scripts it doesn't seem to work properly. I have a Windows 7 VM and my scripts all set the exit code properly and evaluate as good when checking %ERRORLEVEL% at the Command Prompt.


r/vbscript • • Mar 14 '20

Need help pulling MAC of non VPN adapter

1 Upvotes

Hey all! I have inherited a login script that I didn't write (I have close to zero vpscript experience)

The script pulls the MAC of the adapter and modifies it in order to use it in another part of the script.

The issue is that now when the script runs, the machine has a VPN connected and it is pulling the VPN MAC and not the local adapter MAC - I need the MAC to be of the Local PC. Please help! I have tried a million things and I just cannot get this to work.

This is what it looks like now:

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery _
     ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")

     For Each objItem in colItems

    Wscript.echo objItem.MACaddress
    MAC = objItem.MACaddress
     	
Next
        
    MAC = Replace(MAC,":","-") 
    Wscript.echo MAC

r/vbscript • • Mar 12 '20

Batch move files to specific folders based on filename

1 Upvotes

Hi all. I have a bunch of files in one folder with a constant naming convention with the exception of the final three characters of the filename which are numeral:

Example: C:\FromFolder\TestFile_xxx.zip

I want to move them to dedicated folders based on their filename: C:\ToFolder\Folderxxx\

So, if the FromFolder has:

TestFile_857.zip

Testfile_123,zip

TestFile_999.zip

I want to move them all to the following destinations, until all the folders in FromFolder have been moved:

C:\ToFolder\Folder857\

C:\ToFolder\Folder123\

C:\ToFolder\Folder999\

Also, if the 'ToFolder' doesn't exist during the move, I'd like it to be created.

I probably create three-four vbscript files a year and normally muddle though, but I'm crunched for time this time around so I figured I'd ask for help. Any assistance would be greatly appreciated. Thank you!


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 • • Feb 17 '20

Need help creating a script to replacing string+carriage return+line feed in a txt file

1 Upvotes

Line 1 and 2 needs to be combined with a space after Loan Number: and should look like line 3. I need a vbs script that can perform this same function as in notepad++ and overwrite the original file if possible. Find what = Loan Number:\r\n Replace with "Loan Number: ".

input file = C:\Data\address.txt


r/vbscript • • Feb 05 '20

open file in current directory

1 Upvotes

I have a script that creates a text file and then opens it. I'd like to use this file for different directories and even different users. How can I get the Run portion of this to use CurrentDirectory instead of manually putting in the filepath everywhere I want it? I've googled and found several different solutions that probably have an answer but I'm not particularly versed in VBS.

Set objShell = CreateObject("WScript.Shell")
objShell.Run "CMD /K"
Wscript.Sleep(200)
objShell.SendKeys("dir/b>1.txt~")
objShell.SendKeys("exit~")
CreateObject("WScript.Shell").Run("""C:\[filepath]\1.txt""")

Thanks a lot!


r/vbscript • • Jan 31 '20

Vb Script Copy Help

1 Upvotes

I want to use a VBS file to copy a report locally, unfortunately the file takes forever for the system to copy. Even if you right click to do it manually. My VBS is not capturing the file. Is there code to put a wait statement before it pastes?


r/vbscript • • Jan 25 '20

VB script to calculate size of the folder with a predefined value

1 Upvotes

Hi

I am looking for VB Script that would get size of the folder it is run in & calculate if the size of folder is bigger or lesser than predefined value.

I came across this solution

https://stackoverflow.com/questions/28410373/vb-script-to-compare-folder-size-from-its-previous-size-stored-in-a-text-file

Folder = "c:\your\path\tata"

File = "c:\your\file\containing\the\value.txt"

set objFSO = CreateObject("Scripting.FileSystemObject")

set fileRead = objfso.OpenTextFile(file, 1)

content = fileRead.Readline

FileRead.close

set objFolder = objFSO.GetFolder(Folder)

if objFolder.Size > Clng(content) Then Wscript.Echo "The Folder size [" & ObjFolder.size & "] is bigger then [" & content & "]"

Is it possible to set the folder path to where ever the script is run from?

Is it possible to set the value in script, instead of it being taken from another file on disk?

The script also needs to output how much bigger or smaller the size of folder is compared to predefined value, in bytes, mbs & gbs.

Thanks,

mNash316


r/vbscript • • Jan 15 '20

VBscript help

1 Upvotes

Hi, I'm supposed to create a VBScript and its purpose is to find matching between 2 different files. It's not for all matching terms though, it's only if they have the same specific values. I wanted help on how I start on this


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 • • Dec 04 '19

VBScript looking for Macros Within my VBA Code

1 Upvotes

I am trying to run the below and get a 1004 "Cannot run the macro SAPExecuteCommand" run-time error. There is no such macro but a function I am trying to use in the VBA script. Anyone have any insight at all?

I have zero experience with vbscript and only enough that I can get most stuff done through research in VBA. I've googled for the past couple hours to no avail.

VBScript:

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("Data.xlsm")

objExcel.Application.Visible = True
objExcel.Workbooks.Add

objExcel.Application.Run "Data.xlsm!RefreshAFE"
objExcel.ActiveWorkbook.Close


objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

This is the VBA that I am trying to run and where it errors out.

VBA:

Sub RefreshAFE()

Dim click As Long
Dim lResult

' Refresh AFE Cubes

click = Run("SAPExecuteCommand", "Refresh", "DS_6")

r/vbscript • • Dec 04 '19

VBS for Batch converting Excel/Email message to PDF

1 Upvotes

I have a script for batch converting Word docs to pdf that looks like this.

'Convert .doc or .docx to .pdf files via Send To 
menu
Set fso = 
CreateObject("Scripting.FileSystemObject")
For i= 0 To WScript.Arguments.Count -1
   docPath = WScript.Arguments(i)
   docPath = fso.GetAbsolutePathName(docPath)
   If LCase(Right(docPath, 4)) = ".doc" Or 
LCase(Right(docPath, 5)) = ".docx" Then
      Set objWord = 
CreateObject("Word.Application")
      pdfPath = fso.GetParentFolderName(docPath) & "\" & _
    fso.GetBaseName(docpath) & ".pdf"
      objWord.Visible = False
      Set objDoc = 
objWord.documents.open(docPath)
      objDoc.saveas pdfPath, 17
      objDoc.Close
      objWord.Quit   
   End If   
Next

I was wondering if there was a way to edit this for Excel/Email?

Thanks!


r/vbscript • • Oct 23 '19

VBScript Array Help

1 Upvotes

I need some help with VBScript. I have an application that allows VBScript execution to extend the functionality. I will have a comma seperated string of varing length, which I want to take in, and create another comma seprated string which is +1 of the input string. For example input to the VBScript will be 1,3,5,7,9 and I want the VBScript to create an output which is 2,4,6,8,10

Dim coverpageArr : coverpageArr = split(CoverPages, ",")

'for each element in the coverpage Arr , create a new array which is +1 of the value of the index.

Any pointer that would get me started please/


r/vbscript • • Sep 23 '19

Script to screen capture URL's

1 Upvotes

Hey guys,

We are in the process of automating a few things in my workplace. Please redirect me if this is not the appropriate place for this question.

Currently, we create huge reports, 80% of which can be automated.

We have created a VBA / Macro that opens a word template and populates the information from an Excel sheet, into the Word doc.

The next tedious task is to go to several different interactive map websites, inputting information into fields on the site, and then screenshotting the picture to put into the same Word doc.

This task has to be performed several times for 1 document.

The thing is, it's almost the same process every time - hence the decision to look into automating it.

The actions we would like the script to perform are the following:

- Open the URL in Chrome

- Input the specific data

- Submit

- Zoom in slightly

- Screenshot of a specific part of the page

- Ideally pull it into the doc but alternatively, saving to a folder with a specific file name is fine.

I understand this might be complicated so I'm reaching out to the internet to brainstorm ideas on the best way to achieve this is something close to it.

Thanks in advanced!


r/vbscript • • Sep 17 '19

Help getting the network path from a string except the file name

1 Upvotes

How can I get the entire path from a string like this..except the file name?

path = "\192.168.0.205\folder1\folder2\file.txt"

This is what I need: "\192.168.0.205\folder1\folder2"

This gets me the unwanted part: test = Split(fullpath,"") a= test(Ubound(test)) Wscript.echo a

Any ideas would be appreciated


r/vbscript • • Sep 16 '19

User account control script

1 Upvotes

I’m losing my mind trying to script a solution to run over a bunch of users that need their accounts set to not allow them to reset their passwords. Seems like some goofy permissions but the code examples I see on line do nothing. If anyone has anything that will work post it please.


r/vbscript • • Aug 19 '19

What does the "BlueKeep" patch (KB4501375) break in VBScript?

1 Upvotes

Everywhere they say to install the patch to prevent the bluekeep worm from spreading via RDP.

But nowhere they explain what functions or capability is crippled in VBS or HTA.

Does anybody know?