VBA subscript out of range error - vba

Guys here is the code below, Its was working fine for the month of May 05/30/2015. But for some reason it is crashing and giving me subscript of of range error.
I may have changed some links , just trying to conceptually understand what the error is , then debug it. The code is an OLEDB connection and pulls data by month
can you guys take a look
I dont get a line that is causing the error but its the SOI call is when it happens . I am thinking its a connection issue so will try to delete the OLEDB connection and redo it
Sub Update()
'PCAP
Call ReplaceConnectionandRefresh1("PCAP", "zzFS - PCAP- SCRF3", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
'Capital Activity Rec
Call ReplaceConnectionandRefresh1("INVESTRAN DATA", "zzCapital Activity by Position rec - SCRF3", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
'SOI
Call ReplaceConnectionandRefresh1("SOI from JPM investran", "zz_Schedule of Investments", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
'TB
Call ReplaceConnectionandRefresh1("Sheet2", "TB Summary_BS", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
MsgBox ("All Investran data tabs have been refreshed.")
End Sub
Sub ReplaceConnectionandRefresh1(spreadsheet As Variant, DriverName As String, RWFolder As String, dbName As String, ServerName As String)
'Sheets(spreadsheet).Visible = True
'Sheets(spreadsheet).Select
'Sheets(spreadsheet).Range("A1").Select
Set lstObj = Sheets(spreadsheet).ListObjects(1)
Set queryTbl = lstObj.QueryTable
queryTbl.Connection = "OLEDB;Provider=ftiRSOLEDB.RSOLEDBProvider;" _
& "Integrated Security=" & """" & """" _
& ";Location=" & dbName & ";User ID=" & """" & """" _
& ";Initial Catalog=" & dbName & ";Data Source=" & ServerName _
& ";Mode=Read;Persist Security Info=True;Extended Properties="
mycurrentvalue = """" & dbName & """"
mycurrentvalue = mycurrentvalue & "." & """" & RWFolder & """"
mycurrentvalue = mycurrentvalue & "." & """" & DriverName & """"
mycurrentvalue = mycurrentvalue & " " & """"
mycurrentvalue = mycurrentvalue & "begin date=" & Format(Range("BeginDate"), "mm/dd/yyyy") & """"
mycurrentvalue = mycurrentvalue & " " & """"
mycurrentvalue = mycurrentvalue & "End Date=" & Format(Range("EndDate"), "mm/dd/yyyy") & """"
mycurrentvalue = mycurrentvalue & " " & """"
mycurrentvalue = mycurrentvalue & "GL Begin Date=" & Format(Range("BeginDate"), "mm/dd/yyyy") & """"
mycurrentvalue = mycurrentvalue & " " & """"
mycurrentvalue = mycurrentvalue & "GL End Date=" & Format(Range("EndDate"), "mm/dd/yyyy") & """"
mycurrentvalue = mycurrentvalue & " " & """"
mycurrentvalue = mycurrentvalue & "Legal Entity=" & Range("LEID") & """"
mycurrentvalue = mycurrentvalue & " " & """"
mycurrentvalue = mycurrentvalue & "GL Date=" & Format(Range("EndDate"), "mm/dd/yyyy") & """"
mycurrentvalue = mycurrentvalue & " FLAGS[/SILENT]"
Debug.Print mycurrentvalue
queryTbl.CommandText = mycurrentvalue
queryTbl.Refresh BackgroundQuery:=False
End Sub

See if this code helps. I cleaned it up a little bit I think you are having an error because you do not have QueryTable object on the sheet.Option Explicit
Sub Update()
'PCAP
Call ReplaceConnectionandRefresh1(Sheets("PCAP"), "zzFS - PCAP- SCRF3", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
'Capital Activity Rec
Call ReplaceConnectionandRefresh1(Sheets("INVESTRAN DATA"), "zzCapital Activity by Position rec - SCRF3", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
'SOI
Call ReplaceConnectionandRefresh1(Sheets("SOI from JPM investran"), "zz_Schedule of Investments", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
'TB
Call ReplaceConnectionandRefresh1(Sheets("Sheet2"), "TB Summary_BS", "Apollo", "DB_PEFS521", "TSCRLWSQLCLP162\PEFS02")
MsgBox ("All Investran data tabs have been refreshed.")
End Sub
Sub ReplaceConnectionandRefresh1(ByRef shTable As Worksheet, _
ByVal strDriverName As String, _
ByVal strRWFolder As String, _
ByVal strDataBase As String, _
ByVal strServerName As String)
Dim oQueryTbl As QueryTable
Dim strConnection As String
Dim strCommand As String
' Make sure you have query rables on the sheet.
If Not shTable.QueryTables.Count = 0 Then
' Prepare the connection string
strConnection = "OLEDB;Provider=ftiRSOLEDB.RSOLEDBProvider;" _
& "Integrated Security=" & """" & """" _
& ";Location=" & strDataBase & ";User ID=" & """" & """" _
& ";Initial Catalog=" & strDataBase & ";Data Source=" & strServerName _
& ";Mode=Read;Persist Security Info=True;Extended Properties="
' Prepare the command
strCommand = """" & strDataBase & """"
strCommand = strCommand & "." & """" & strRWFolder & """"
strCommand = strCommand & "." & """" & strDriverName & """"
strCommand = strCommand & " " & """"
strCommand = strCommand & "begin date=" & Format(Range("BeginDate").Value, "mm/dd/yyyy") & """"
strCommand = strCommand & " " & """"
strCommand = strCommand & "End Date=" & Format(Range("EndDate").Value, "mm/dd/yyyy") & """"
strCommand = strCommand & " " & """"
strCommand = strCommand & "GL Begin Date=" & Format(Range("BeginDate").Value, "mm/dd/yyyy") & """"
strCommand = strCommand & " " & """"
strCommand = strCommand & "GL End Date=" & Format(Range("EndDate").Value, "mm/dd/yyyy") & """"
strCommand = strCommand & " " & """"
strCommand = strCommand & "Legal Entity=" & Range("LEID").Value & """"
strCommand = strCommand & " " & """"
strCommand = strCommand & "GL Date=" & Format(Range("EndDate").Value, "mm/dd/yyyy") & """"
strCommand = strCommand & " FLAGS[/SILENT]"
Debug.Print strCommand
' Add the connection information and refresh.
With shTable.QueryTables(1)
.Connection = strConnection
.CommandText = strCommand
.Refresh BackgroundQuery:=False
End With
Else
MsgBox "There is not query tables in sheet " & shTable.Name, vbOKOnly + vbCritical, "Error"
End If
End Sub
Hope this helps :)

Related

How to change font color for updated Access data in Outlook mail

In Access 2010 I have tables, e.g. Employee(Pracownicy). I can update the data in the table using the subform and the update button.
Updating the data in the subform automatically generates an Outlook mail containing the data in the updated record.
I need to change font color for updated data in the mail body.
The code to update the data and generate e-mail:
Private Sub cmdUpdate2_Click()
CurrentDb.Execute "update Pracownicy" & _
" SET Identyfikator='" & Me.txtID & "'" & _
", Imie='" & Me.txtImie & "'" & _
", Nazwisko ='" & Me.txtNazwisko & "'" & _
", Wiek ='" & Me.txtWiek & "'" & _
", Data_urodzenia ='" & Me.txtData & "'" & _
", Miejsce_urodzenia ='" & Me.txtMiejsce & "'" & _
", Miejscowosc ='" & Me.txtMiejscowosc & "'" & _
", Plec ='" & Me.txtPlec & "'" & _
" where Identyfikator='" & Me.txtID & "'"
'------------------------------------SEND EMAIL----------------------
'Dim varName As Variant
'Dim strUCC As String
Dim varSubject As Variant
Dim varBody As Variant
Dim Poczta As Object
Dim MojMail As Object
On Error Resume Next
'varName = ""
varSubject = "Employer List "
varBody = "Hello" & _
"<br><br>Employer List: " & _
"<br><br><B>Identyfikator:</B> " & Me.txtID & " " & _
"<br><B>Imie:</B> " & Me.txtImie & " " & _
"<br><B>Nazwisko:</B> " & Me.txtNazwisko & " " & _
"<br><B>Wiek:</B> " & Me.txtWiek & " " & _
"<br><B>Data urodzenia:</B> " & Me.txtData & " " & _
"<br><B>Miejsce urodzenia:</B> " & Me.txtMiejsce & " " & _
"<br><B>Miejscowosc:</B> " & Me.txtMiejscowosc & " " & _
"<br><B>Plec:</B> " & Me.txtPlec & " "
Set Poczta = CreateObject("outlook.application")
Set MojMail = Poczta.createitem(0)
With MojMail
'.To =
'.BCC =
.subject = varSubject
'.ReadReceiptRequested = True
'.originatorDeliveryReportRequested = True
.htmlbody = varBody & "<br>"
.display
'.send
End With
Set Poczta = Nothing
Set MojMail = Nothing
If Err.Number <> 0 Then
MsgBox ("Atention")
End If
On Error GoTo 0
'------------------------------------------------------------------------
DoCmd.Close
MsgBox ("End Update")
End Sub
I think this becomes more of an HTML question rather than VBA. Try adding a FONT tag to the following line and see if that works for you.
"<br><br><B><font color="red">Identyfikator:</font></B> " & Me.txtID & " " & _

Syntax error in UPDATE statement. via cmd.nonexecutequery

If Me.TextBox1.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO Table1(CandidateID, Fname, Mname, Lname, Partylist, Pst, course) " & _
" VALUES (" & Me.TextBox1.Text & ", '" & Me.TextBox2.Text & "', '" & Me.TextBox3.Text & "', '" & _
Me.TextBox4.Text & "', '" & Me.ComboBox1.Text & "', '" & Me.ComboBox2.Text & "', '" & Me.ComboBox3.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE table " & _
" SET CandidateID=" & Me.TextBox1.Text & _
", Fname='" & Me.TextBox2.Text & "'" & _
", Mname='" & Me.TextBox3.Text & "'" & _
", Lname='" & Me.TextBox4.Text & "'" & _
", Partylist='" & Me.ComboBox1.Text & "'" & _
", Pst='" & Me.ComboBox2.Text & "'" & _
", Course='" & Me.ComboBox3.Text & "'" & _
" WHERE CandidateID=" & Me.TextBox1.Tag
cmd.ExecuteNonQuery()
cmd.CommandText = "UPDATE Table1 " & _
" SET CandidateID=" & Me.TextBox1.Text & _
", Fname='" & Me.TextBox2.Text & "'" & _
", Mname='" & Me.TextBox3.Text & "'" & _
", Lname='" & Me.TextBox4.Text & "'" & _
", Partylist='" & Me.ComboBox1.Text & "'" & _
", Pst='" & Me.ComboBox2.Text & "'" & _
", Course='" & Me.ComboBox3.Text & "'" & _
" WHERE CandidateID=" & Me.TextBox1.Tag
cmd.ExecuteNonQuery()
my table was incorrect.
thank you for those who replied to my thread

Excel OLEDB connection issue

Below is the code: What I am trying to do is made the refresh of data more under my control. So when I "GL date" from 03/31/2014 to 04/31/2014. The connection picks up the april data.
The error I am getting is With Selection.QueryTable, thats where it breaks.
The table starts at cell "A1" on the PCAP tab
Sub Update()
Call ReplaceConnectionandRefresh1("PCAP", "zzFS - PCAP- SCRF3", "Apollo", "zzFS - PCAP- SCRF3")
End Sub
Sub ReplaceConnectionandRefresh1(spreadsheet As Variant, DriverName As String, RWFolder As String, CombinedNumber As String)
Sheets(spreadsheet).Visible = True
Sheets(spreadsheet).Select
Sheets(spreadsheet).Range("A1").Select
With Selection.QueryTable
.Connection = "OLEDB;Provider=ftiRSOLEDB.RSOLEDBProvider;" _
& "Integrated Security=" & """" & """" _
& ";Location=" & dbName & ";User ID=" & """" & """" _
& ";Initial Catalog=" & dbName & ";Data Source=" & ServerName _
& ";Mode=Read;Persist Security Info=True;Extended Properties="
.MaintainConnection = False
MYCURRENTVALUE = .CommandText
End With
MYCURRENTVALUE = """" & dbName & """"
MYCURRENTVALUE = MYCURRENTVALUE & "." & """" & RWFolder & """"
MYCURRENTVALUE = MYCURRENTVALUE & "." & """" & DriverName & """"
MYCURRENTVALUE = MYCURRENTVALUE & " "
MYCURRENTVALUE = MYCURRENTVALUE & """" & "Legal Entity=" & CombinedNumber & """"
MYCURRENTVALUE = MYCURRENTVALUE & " " & """"
MYCURRENTVALUE = MYCURRENTVALUE & "GL Date=" & Format("03/31/2014", "mm/dd/yyyy") & """"
MYCURRENTVALUE = MYCURRENTVALUE & " FLAGS[/SILENT] "
With Selection.QueryTable
.CommandText = MYCURRENTVALUE
.Refresh BackgroundQuery:=False
End With
End Sub
Perhaps the range "A1" does not contain the Query table object. Also try to use Selection and Select as little as possible (Actually you will need it in very rare occasions) Rather use the actual object.
Option Explicit
Sub Update()
Call ReplaceConnectionandRefresh1("PCAP", "zzFS - PCAP- SCRF3", "Apollo", "zzFS - PCAP- SCRF3")
End Sub
Sub ReplaceConnectionandRefresh1(spreadsheet As String, _
DriverName As String, _
RWFolder As String, _
CombinedNumber As String)
Dim oQueryTable As QueryTable
Dim strConnnection As String
Dim strCommand As String
' Grab the query Table from the sheet. I am grabbing the first one
' adjust if there is more.
Set oQueryTable = Sheets(spreadsheet).QueryTables(1)
Sheets(spreadsheet).Visible = True
Sheets(spreadsheet).Select
Sheets(spreadsheet).Range("A1").Select
' Create connection string
strConnnection = "OLEDB;Provider=ftiRSOLEDB.RSOLEDBProvider;" _
& "Integrated Security=" & """" & """" _
& ";Location=" & dbName & ";User ID=" & """" & """" _
& ";Initial Catalog=" & dbName & ";Data Source=" & ServerName _
& ";Mode=Read;Persist Security Info=True;Extended Properties="
'Create connection command
strCommand = """" & dbName & """"
strCommand = strCommand & "." & """" & RWFolder & """"
strCommand = strCommand & "." & """" & DriverName & """"
strCommand = strCommand & " "
strCommand = strCommand & """" & "Legal Entity=" & CombinedNumber & """"
strCommand = strCommand & " " & """"
strCommand = strCommand & "GL Date=" & Format("03/31/2014", "mm/dd/yyyy") & """"
strCommand = strCommand & " FLAGS[/SILENT] "
' Actually update the connection.
With oQueryTable
.Connection = strConnnection
.MaintainConnection = False
.CommandText = strCommand
.Refresh BackgroundQuery:=False
End With
End Sub
Also note that there is a variable "dbName" that is not declared or passed as argument.
I hope this helps :)

How to add an incremental count (version) to a string (file) in Excel/VBA?

I have tried a lot of different things, and it seems like I cannot get it to work. So basically, this is a small piece of my complete code.
I am using Microsoft Scripting Runtime to save the file, using the FileExists() to check if the file actually exist before saving.
This is working fine if I remove the IF-statement/Loop.
However, now it feels like FileExists won´t find the string, MyFilePath, when I run it with the IF/Loop. (getdirsubparentpath is a function)
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
MyFilePath = getDirSubParentPath & MyFile
' Look for the MyFilePath, if it exists then
' Add "-1" after the week number, if 1 exists, add 2, etc.
If Len(Dir(MyFilePath)) <> 0 Then
version = 0
Do
version = version + 1
MyFilePath = Dir(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv")
Loop Until Len(Dir(MyFilePath)) < 0
End If
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
'Dim fso As New FileSystemObject
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFilePath, vbCritical, "Error"
End If
Set fso = Nothing
End Sub
' Get Parent Sub Directory Path
Function getDirSubParentPath()
getDirSubParentPath = ThisWorkbook.Path & Application.PathSeparator & "CSV" & Application.PathSeparator & "Parent" & Application.PathSeparator
End Function
I finally manage to create a solution that seems viable. However, the code could use some cleaning up :) But it gets the job done.
So basically, I am having some issues with the loop. It will return a file named W16-0 (which should actual just be W16). It should only add the "-X" if W16 is found. So the incremental order should be W16, W16-1, W16-2, etc.
What I am doing is that I try to locate if there is a W16-0 and then replace it with W16. Furthermore, it seems like the loop will give me one higher than the amount of files I have. So that is where I also got an error. So if I had a W16-4, it would ask the macro to find and open a file named W16-5, which would obviously not exist.
If somebody could help me clean up the code, I would be really thankful!
Sub RemoveCommasDoubleQ()
'
' Enable a reference to 'Microsft Scripting Runtime'
' under VBA menu option Tools > References
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
'MyFilePath = ThisWorkbook.Path & "\CSV\Parent\" & MyFile
MyFilePath = getDirSubParentPath & MyFile
Debug.Print MyFilePath
Debug.Print "BEFORE LOOP"
'version = 1
Do While Len(Dir(MyFilePath)) <> 0
'// If it does, then append a _000 to the name
'// Change _000 to suit your requirement
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
'// Increment the counter
version = version + 1
'// and go around again
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "IF LOOP"
End If
Loop
Debug.Print MyFilePath
Debug.Print "LOOP"
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv") = False Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version - 2 & " " & UserName & ".csv"
MsgBox getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "her it should be 0"
End If
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
Debug.Print "HER ER VI"
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
Debug.Print "------"
Debug.Print MyFilePath
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv") = True Then
MsgBox "Found the W-0"
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
End If
Debug.Print "Found 0?"
Debug.Print MyFilePath
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFile, vbCritical, "Error"
End If
Set fso = Nothing
End Sub

Send mail using VB Script?

I have the following code to monitor a drive. Now I an getting Echo for each file creation or deletion event.
Is there and way to modify the WScript.Echo to send a mail notification?
strDrive = "c"
arrFolders(0) = strDrive & "\\\\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
'Loop throught the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" & " and TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub"
WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Instead of Echoing like below:
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub"
I want to send a mail like this:
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "
Set outobj = CreateObject("Outlook.Application")
Set mailobj = outobj.CreateItem(0)
With mailobj
.To = toAddress
.Subject = Subject
.HTMLBody = strHTML
.Send
End With
" & VbCrLf & "End Sub"
Is it possible or is there an other way to do this..?
I don't know what server do you use, but on Windows 2003 and 2008 e.g. you can use CDO object to create a email. You might use a smart host to send your email to.
Check this link: http://www.paulsadowski.com/wsh/cdo.htm
Also you can choose any free email component to create a email and use a smtp server to send your email. Or check this side where you can use a component including many examples how to do it: http://www.chilkatsoft.com/email-activex.asp.
** UPDATED **
This Script checks and send a email as you requestted:
strDrive = "d:"
Dim arrFolders(0) : arrFolders(0) = strDrive & "\\\\"
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
'Loop throught the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
WScript.Echo "setup for folder: " & strFolder & vbLf
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * " _
& "FROM __InstanceOperationEvent " _
& "WITHIN 1 " _
& "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" _
& " AND TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & vbLf _
& " Wscript.Echo objObject.TargetInstance.PartComponent" & vbLf _
& " SendMail(objObject.TargetInstance.PartComponent)" & vbLf _
& "End Sub"
'WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Function SendMail(vBody)
Dim oMail : Set oMail = CreateObject("CDO.Message")
'Name or IP of Remote SMTP Server
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "your.smtp.server"
oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMail.Configuration.Fields.Update
oMail.Subject = "Email Watch Info Message"
oMail.From = "alert#yourdomain.net"
oMail.To = "target#yourdomain.net"
oMail.TextBody = vBody
oMail.Send
End Function
Correct the settings in the send mail function and your are fine.
In theory, the VBSendMail DLL should be able to do what you want.