VBScript Error Message and Handling - excel

So I have this Auto Email Script, it all works fine but the problem I am having is that when an email pops up that isn't valid it will error out and quit, what I am wondering is, is there a way to tell it if there is an error skip that record and move onto the next one?
Set objMessage = CreateObject("CDO.Message")
Set app = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("##############").Files
If LCase(fso.GetExtensionName(f)) = "xls" Then
Set wb = app.Workbooks.Open(f.Path)
set sh = wb.Sheets("Auto Email Script")
row = 4
email = sh.Range("A" & row)
LastRow = sh.UsedRange.Rows.Count
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim f
Set f = fso.OpenTextFile("#####################.txt", ForReading)
BodyText = f.ReadAll
For r = row to LastRow
If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
email = sh.Range("A" & row)
sh.Range("I" & row).Value = "Sent"
row = row + 1
End if
If email = "" Then
Wscript.Quit
End if
objMessage.Subject = "Billing: Meter Read"
objMessage.From = "################"
objMessage.To = email
objMessage.TextBody = BodyText
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "################"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
objMessage.Send
Next
wb.Save
f.Close
Set f = Nothing
Set fso = Nothing
wb.Close
End If
Next

It's still not clear to me what you mean by "invalid address". If you mean a malformed address you could validate it e.g. with a regular expression:
Set re = New RegExp
re.Pattern = "^[a-z0-9][a-z0-9._]*#[a-z][a-z0-9-]*\.[a-z]+$"
re.IgnoreCase = True
If re.Test(email) Then
'send mail
End If
Note that the expression above is rather conservative and covers only a safe subset of all potentially valid addresses.
If you mean that an address is rejected by your mail server you need to enable error handling for objMessage.Send as #mehow suggested:
On Error Resume Next
objMessage.Send
If Err Then WScript.Echo Hex(Err.Number) & ": " & Err.Description
On Error Goto 0

Related

how to insert table from excel with specific value into outlook using vbscripting

I am trying to send email using outlook and vbs.
Parse through excel
take subject, email, name, attachment etc from there. the based on attachment name, i need to insert table from attachment excel into body of email.
set app = CreateObject("Excel.Application")
' get current path
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
strPath = WshShell.CurrentDirectory
Set WshShell = Nothing
'converting csv to xlsx
Set wb = app.Workbooks.Open (strPath+"\"+"rbo1.csv")
WB.SaveAs Replace(WB.FullName, ".csv", ".xlsx"), 51
WB.Close False
wb.close 0
set wb =nothing
Set wb = app.Workbooks.Open (strPath+"\"+"rbo1.xlsx")
set sh = wb.Sheets(1)
row = 2
set name sh.cells("C" & row)
set email = sh.Range("L" & row)
set subject = sh.Range("M" & row)
set attach = sh.Range("N" & row)
Set Cur_date = sh.range("A" & row)
Set Prev_date = sh.range("B" & row)
Set Prev_Bal = sh.range("G" & row)
Set Cur_Bal = sh.range("H" & row)
LastRow = sh.UsedRange.Rows.Count
For r = row to LastRow
If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
SendMessage email, name, subject, TRUE, attach, strPath, Cur_date, Prev_date,_
Prev_Bal , Cur_Bal
row = row + 1
name sh.cells("C" & row)
email = sh.Range("L" & row)
subject = sh.Range("M" & row)
attach = sh.Range("N" & row)
Cur_date = sh.range("A" & row)
Prev_date = sh.range("B" & row)
Prev_Bal = sh.range("G" & row)
Cur_Bal = sh.range("H" & row)
End if
Next
wb.close
set wb = nothing
set app = nothing
Sub SendMessage(EmailAddress, DisplayName, Subject, DisplayMsg, AttachmentPath, strPath, Cur_date, Prev_date, Prev_Bal , Cur_Bal)
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
objXl = app.Workbooks.Open(strPath+"\"+AttachmentPath)
htmlmsg = extracttablehtml(objXl.worksheets(1), objXl.worksheets(1).usedRange)
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(0)
With objOutlookMsg
' Add the To recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add(EmailAddress)
objOutlookRecip.resolve
objOutlookRecip.Type = 1
' Set the Subject, Body, and Importance of the message.
.Subject = Subject
.bodyformat = 3
.Importance = 2 'High importance
.HTMLBody = "<table> <br> Dear Sir, <br><br> given under details the change balance+"<br> for any query please call under signed<br><br>" + htmlmsg
' Should we display the message before sending?
If DisplayMsg Then
.Display
Else
.Save
' .Send
End If
End With
objXl.close 0
set objXl = Nothing
Set objOutlook = Nothing
End Sub
Function extracttablehtml(ws, rng)
Dim HtmlContent
Dim i
Dim j
On Error GoTo 0
HtmlContent = "<table>"
For i = 1 To rng.Rows.Count
HtmlContent = HtmlContent & "<tr>"
For j = 1 To rng.Columns.Count
HtmlContent = HtmlContent & "<td>" & ws.Cells(i, j).Value & "</td>"
Next
HtmlContent = HtmlContent & "</tr>"
Next
HtmlContent = HtmlContent & "</table>"
extracttablehtml = HtmlContent
End Function
two problems
extracttablehtml is not working as desired please advise whats the problem
now modification i need to do is to choose only rows based on given criteria
thanks in advance

Macro not working for fetching data from Active Directory

Recently I changed my laptop and below given macro is not working in it. where as in my old machine it is still working. I cross checked all the references and enable it as per my old machine. I also cross checked with some other guys and they told me to use ADODB.Connection line in below code.
Also When I checked macro line by line items by pressing F8 key its is showing blank in "idapstr" line where as in old machine when using same macro its working fine.
Error code is on below line code "Set x = GetObject(ldapstr)" is mentioned below :-
**
" run time Error -2147023541 (8007054b)
Automation Error
The Specified domain either does not exist or could not be contacted."**
Can anybody help me out how to add the "ADODB.Connection" code or how to adjust this existing code ?
Public Sub UpdateResourceInfoNew()
Application.Calculation = xlCalculationManual
Dim auxDoc As New MSHTML.HTMLDocument, HTMLDoc As MSHTML.HTMLDocument
Dim rw As IHTMLTableRow
Dim table1 As IHTMLTable
Dim x As IADs
Dim lo As Excel.ListObject
Dim lr As Excel.ListRow
Dim rng As Range
Dim col As Column
Dim signum, name, ldapstr, relation As String
Dim urlText As Variant
Dim keyVal As Variant
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Worksheets("ASSIGNMENTS")
Dim responseDict As Dictionary
On Error Resume Next
Dim answer As Integer
answer = MsgBox("Did you updated the Authorization Key in sheet ?", vbQuestion + vbYesNo)
If answer = vbYes Then
Set lo = ActiveWorkbook.Worksheets("ASSIGNMENTS").ListObjects("ASSIGNMENTS")
For Each lr In lo.ListRows
Set rng = lr.Range
signum = UCase(rng.Cells.Columns(lo.ListColumns("SIGNUM").Index).Value)
name = rng.Cells.Columns(lo.ListColumns("NAME").Index).Value
updateFlag = rng.Cells.Columns(lo.ListColumns("UPDATE_RES_INFO").Index).Value
If signum <> "" And updateFlag = 1 Then
ldapstr = "LDAP://CN=" & signum & ",OU=CA,OU=User,OU=P001,OU=ID,OU=Data,DC=XXXXXXXX,DC=se"
Set x = GetObject(ldapstr)
x.GetInfoEx Array("CN", "displayName", "givenName", , "email", "sn", "homePhone", "title", "department", "company", "l", "Manager", "country"), 0
auxCN = UCase(x.Get("CN"))
If (auxCN = signum) Then
rng.Cells.Columns(lo.ListColumns("SIGNUM").Index).Value = UCase(signum)
rng.Cells.Columns(lo.ListColumns("NAME").Index).Value = Application.WorksheetFunction.Proper(x.Get("displayName"))
rng.Cells.Columns(lo.ListColumns("RELATION").Index).Value = Application.WorksheetFunction.Proper(x.Get("homePhone"))
rng.Cells.Columns(lo.ListColumns("TITLE").Index).Value = x.Get("title")
rng.Cells.Columns(lo.ListColumns("DEPARTMENT").Index).Value = UCase(x.Get("department"))
rng.Cells.Columns(lo.ListColumns("COMPANY").Index).Value = UCase(x.Get("company"))
rng.Cells.Columns(lo.ListColumns("COUNTRY").Index).Value = UCase(x.Get("country"))
rng.Cells.Columns(lo.ListColumns("LAST NAME").Index).Value = Application.WorksheetFunction.Proper(x.Get("sn"))
rng.Cells.Columns(lo.ListColumns("FIRST NAME").Index).Value = Application.WorksheetFunction.Proper(x.Get("givenName"))
rng.Cells.Columns(lo.ListColumns("E-MAIL").Index).Value = x.Get("mail")
rng.Cells.Columns(lo.ListColumns("HOME BASE").Index).Value = UCase(x.Get("l"))
rng.Cells.Columns(lo.ListColumns("UPDATE_RES_INFO").Index).Value = 2
Set responseDict = New Dictionary
url_prefix = "XXXXXXX"
url_suffix = signum_rng
Application.DisplayAlerts = False
On Error Resume Next
Dim returnVal As String
Dim httpObject As Object, item As Object
Set httpObject = CreateObject("MSXML2.XMLHTTP")
URL = url_prefix & Trim(signum)
sAuthorization = Worksheets("Authentication key").Range("G4").Value
httpObject.Open "GET", URL, False
httpObject.setRequestHeader "Authorization", sAuthorization & EncodeBase64
httpObject.Send
sGetResult = httpObject.responseText
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", URL, False
.Send
urlText = Split(Replace(Replace(Replace(Replace(.responseText, "{", ""), "[", ""), "}", ""), "]", ""), ",""")
End With
responseDict.RemoveAll
For i = 0 To UBound(urlText)
urlText(i) = Replace(urlText(i), Chr(34), "")
keyVal = Split(urlText(i), ":")
responseDict.Add keyVal(0), keyVal(1)
Next i
If Split(urlText(34), ":")(1) <> "null" Or Len(Split(urlText(34), ":")(1)) <> 0 Then
rng.Cells.Columns(lo.ListColumns("PERSONNEL NUMBER").Index).Value = Split(urlText(34), ":")(1)
End If
If Split(urlText(11), ":")(1) <> "null" Or Len(Split(urlText(11), ":")(1)) <> 0 Then
rng.Cells.Columns(lo.ListColumns("JOB ROLE").Index).Value = Split(urlText(11), ":")(1)
End If
If Split(urlText(30), ":")(1) <> "null" Or Len(Split(urlText(30), ":")(1)) <> 0 Then
rng.Cells.Columns(lo.ListColumns("POSITION NAME").Index).Value = Split(urlText(30), ":")(1)
End If
If Split(urlText(4), ":")(1) <> "null" Or Len(Split(urlText(4), ":")(1)) <> 0 Then
rng.Cells.Columns(lo.ListColumns("LINE MANAGER").Index).Value = Split(urlText(4), ":")(1)
End If
If Split(urlText(38), ":")(1) <> "null" Or Len(Split(urlText(38), ":")(1)) <> 0 Then
rng.Cells.Columns(lo.ListColumns("COUNTRY").Index).Value = Split(urlText(38), ":")(1)
End If
If Split(urlText(22), ":")(1) <> "null" Or Len(Split(urlText(22), ":")(1)) <> 0 Then
rng.Cells.Columns(lo.ListColumns("MOBILE").Index).Value = Split(urlText(22), ":")(1)
End If
If Split(urlText(32), ":")(1) <> "null" Or Len(Split(urlText(32), ":")(1)) <> 0 Then
rng.Cells.Columns(lo.ListColumns("COST CENTRE").Index).Value = Split(urlText(32), ":")(1)
End If
Application.DisplayAlerts = True
Else
rng.Cells.Columns(lo.ListColumns("UPDATE_RES_INFO").Index).Value = 3
End If
End If
DoEvents
Next lr
MsgBox ("RP Updated")
Else
MsgBox "Please update the Authorization Key first"
End If
End Sub
I am trying to fetch few columns details from Active Directory based on user name in our code we are using as "Signum", due to basic user of VBA I am not able to find out the issue so come to this forum if any user any help me out.

VBScript Write to Excel not writing

What I'm trying to accomplish is searching multiple computers for event code 41 (unexpected shutdown) in the windows system log, then write that into an excel file for each instance for each computer.
I receive no errors, but nothing is ever written into the excel file. I set up an echo to make sure it was reaching the correct part of the loop (it does!) and I set a literal entry to see if there was an error with the variables (it didn't write). At this point, I'm at a loss.
' https://technet.microsoft.com/library/ee176684.aspx
' http://blogs.technet.com/b/heyscriptingguy/archive/2009/04/06/how-can-i-check-my-event-logs.aspx
' http://stackoverflow.com/questions/21738159/extracting-error-logs-from-windows-event-viewer
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("H:\Chris Created Stuffs\Windows Stuffs\check_error_41.xlsx")
objExcel.Visible = False
i = 1
x = 0
'On error resume next
'This is the code that will read the computer names off of the
'appropriate spreadhseet
Do Until objExcel.Cells(i, 1).Value = ""
ReDim Preserve strPC(x)
strPC(x) = objExcel.Cells(i, 1).Value
i = i + 1
x = x + 1
Loop
'And this is the code that will write the success or failure
'data in the Excel spreadsheet
Set objSheet1 = objWorkbook.sheets("Missed")
Set objSheet2 = objWorkbook.sheets("Sheet1")
'Set objSheet1 = objExcel.ActiveWorkbook.Worksheets(1)
'Set objSheet2 = objExcel.ActiveWorkbook.Worksheets(2)
f = 1
m = 1
'Set obj = CreateObject("Scripting.FileSystemObject")
For Each strPC In strPC
Set objWMIService = GetObject("winmgmts:\\" & strPC & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_NTLogEvent WHERE LogFile='System'")
If Err.Number <> 0 Then
'objSheet1.Add
objSheet1.Cells(f, 1).Value = strPC
objSheet1.Cells(f, 2).Value = err.number
f = f + 1
Err.clear
Else
For Each objEvent in colItems
If objEvent.EventCode = 41 Then
'writeLog "Event Code: " & objEvent.EventCode
'writeLog "Event Identifier: " & objEvent.EventIdentifier
'writeLog "Logfile: " & objEvent.Logfile
'writeLog "Message: " & objEvent.Message
'writeLog "Record Number: " & objEvent.RecordNumber
'writeLog "Source Name: " & objEvent.SourceName
'writeLog "Time Generated: " & objEvent.TimeGenerated
'writeLog "Time Written: " & objEvent.TimeWritten
'objSheet2.Add
objSheet2.Cells(m,1).Value = strPC
objSheet2.Cells(m,2).Value = objEvent.EventCode
objSheet2.Cells(m,3).Value = objEvent.EventIdentifier
objSheet2.Cells(m,4).Value = objEvent.Logfile
objSheet2.Cells(m,5).Value = objEvent.Message
objSheet2.Cells(m,6).Value = objEvent.RecordNumber
objSheet2.Cells(m,7).Value = objEvent.SourceName
objSheet2.Cells(m,8).Value = objEvent.TimeGenerated
objSheet2.Cells(m,9).Value = objEvent.TimeWritten
objSheet2.Cells(m,10).Value = "Listen!"
m = m + 1
wscript.echo "We Got One!!!!"
Else
m = m + 1
End If
Next
Err.clear
End If
Next
objExcel.ActiveWorkbook.Save
objExcel.Quit
wscript.echo "Done"
I think your primary problem was ignoring the Workbook Object and Worksheet Object. In this code:
Do Until objExcel.Cells(i, 1).Value = ""
ReDim Preserve strPC(x)
strPC(x) = objExcel.Cells(i, 1).Value
i = i + 1
x = x + 1
Loop
Nothing is actually being pulled from the worksheet. I've had to guess a little as to the actual origin but the syntax is correct; you may have to make specific adjustments to your own worksheet layout.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True 'False
Set objWorkbook = objExcel.Workbooks.Open("H:\Chris Created Stuffs\Windows Stuffs\check_error_41.xlsx")
i = 1
x = 0
'On error resume next
'This is the code that will read the computer names off of the appropriate spreadhseet
Do Until objWorkbook.Worksheets(1).Cells(i, 1).Value = ""
ReDim Preserve strPCs(x)
strPCs(x) = objWorkbook.Worksheets(1).Cells(i, 1).Value
'msgbox objWorkbook.Worksheets(1).Cells(i, 1).Value
i = i + 1
x = x + 1
Loop
'And this is the code that will write the success or failure data in the Excel spreadsheet
Set objSheet1 = objWorkbook.Worksheets("Missed")
Set objSheet2 = objWorkbook.Worksheets("Sheet1")
f = 1
m = 1
For Each strPC In strPCs
Set objWMIService = GetObject("winmgmts:\\" & strPC & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_NTLogEvent WHERE LogFile='System'")
If Err.Number <> 0 Then
'objSheet1.Add
objSheet1.Cells(f, 1).Value = strPC
objSheet1.Cells(f, 2).Value = err.number
f = f + 1
Err.clear
Else
For Each objEvent in colItems
If objEvent.EventCode = 41 Then
'writeLog "Event Code: " & objEvent.EventCode
'writeLog "Event Identifier: " & objEvent.EventIdentifier
'writeLog "Logfile: " & objEvent.Logfile
'writeLog "Message: " & objEvent.Message
'writeLog "Record Number: " & objEvent.RecordNumber
'writeLog "Source Name: " & objEvent.SourceName
'writeLog "Time Generated: " & objEvent.TimeGenerated
'writeLog "Time Written: " & objEvent.TimeWritten
'objSheet2.Add
objSheet2.Cells(m, 1).Value = strPC
objSheet2.Cells(m, 2).Value = objEvent.EventCode
objSheet2.Cells(m, 3).Value = objEvent.EventIdentifier
objSheet2.Cells(m, 4).Value = objEvent.Logfile
objSheet2.Cells(m, 5).Value = objEvent.Message
objSheet2.Cells(m, 6).Value = objEvent.RecordNumber
objSheet2.Cells(m, 7).Value = objEvent.SourceName
objSheet2.Cells(m, 8).Value = objEvent.TimeGenerated
objSheet2.Cells(m, 9).Value = objEvent.TimeWritten
objSheet2.Cells(m, 10).Value = "Listen!"
m = m + 1
'wscript.echo "We Got One!!!!"
'do not add to m on no-write; it only creates blank rows
End If
Next
Err.clear
End If
Next
'objWorkbook.Close True
'objExcel.Quit
wscript.echo "Done"
I've commented out the code lines to make the Excel application object hidden as to save asn close it in order that you can observe the process. Uncomment them once you are happy with the process.

How to create a contact in Outlook with Excel data?

I have an Excel sheet that has a list of contact names, company names and email addresses.
I want to export these to Outlook.
I have done some code to delete current entries in a contact folder using VBA from Excel, but when adding a new contact, I am getting a 438 Runtime error.
Code to add a contact:
Sub addnewcontacts()
Dim runoutlook As Outlook.Application
Set runoutlook = CreateObject("Outlook.Application")
Set findnamespace = runoutlook.GetNamespace("MAPI")
Set activefolder = findnamespace.Folders
n = 1
Do Until activefolder.Item(n) = "user#domain.co.uk"
n = n + 1
Loop
Set myfolder = activefolder.Item(n)
Set myfolder2 = myfolder.Folders("Contacts").Folders("CustGBP")
lastrow = Sheets("Data").Range("A" & Sheets("Data").Rows.Count).End(xlUp).Row
For i = 1 To lastrow
Sheets("Sage Data").Activate
If ActiveSheet.Range("C" & i).Value = "" Then
' IT BREAKS AT THIS LINE
Set olitem = myfolder2.CreateItem(olContactItem)
With olitem
.FullName = Trim(Range("A" & i).Value).
.Company = Trim(Range("B" & i).Value)
.Email1Address = Range("G" & i).Value
End With
olitem.Save
End If
Next i
End Sub
Working delete code:
Sub outlookdelete()
Dim runoutlook As Outlook.Application
Set runoutlook = CreateObject("Outlook.Application")
Set findnamespace = runoutlook.GetNamespace("MAPI")
Set activefolder = findnamespace.Folders
n = 1
Do Until activefolder.Item(n) = "user#domain.co.uk"
n = n + 1
Loop
Set myfolder = activefolder.Item(n)
Set myfolder2 = myfolder.Folders("Contacts").Folders("CustGBP")
Do
For Each ContactItem In myfolder2.Items
ContactItem.Delete
Next ContactItem
' this is in as otherwise it would only delete a handful
' each time it ran for some reason
Loop Until myfolder2.Items.Count = 0
End Sub
You have to create the item from the application itself (i.e. your runoutlook Outlook Object) and then move it to the desired folder. Starting at where you encounter the error, you can update your code with the following
// Creates a contact Item in the default Contacts folder
Set olitem = runoutlook.CreateItem(olContactItem)
With olitem
.FullName = Trim(Range("A" & i).Value)
.Company = Trim(Range("B" & i).Value) ' may need to change to "CompanyName"
.Email1Address = Range("G" & i).Value
.Move DestFldr:=myfolder2 // moves the contact to the indicated folder
.Save
End With
As for the deletion of all the contacts, you can try this code instead
Do While myfolder2.Items.Count <> 0
myfolder2.Items.Remove (1)
Loop
This is how I managed to get it working myself
For i = 1 To lastrow
Sheets("Data").Activate
If ActiveSheet.Range("C" & i).Value = "" Then
Set olitem = myfolder2.Items.Add(olContactItem)
With olitem
.FullName = Trim(Range("A" & i).Value)
.CompanyName = Trim(Range("B" & i).Value)
.Email1Address = Range("G" & i).Value
.Save
End With
End If
Application.StatusBar = "Updating Contacts: " & Format(i / lastrow, "Percent") & " Complete"
Next i

VBScript Cannot Find file Specified Server 2003

I have the following code:
set app = CreateObject("Excel.Application")
Set wb = app.Workbooks.Open("Y:\Billing_Common\autoemail\*.xls")
set sh = wb.Sheets("Auto Email Script")
row = 2
name = "Customer"
email = sh.Range("A" & row)
subject = "Billing"
the = "the"
LastRow = sh.UsedRange.Rows.Count
For r = row to LastRow
If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
SendMessage email, name, subject, TRUE, _
NULL, "Y:\Billing_Common\autoemail\Script\energia-logo.gif", 143,393
row = row + 1
email = sh.Range("A" & row)
End if
Next
wb.close
set wb = nothing
set app = nothing
Sub SendMessage(EmailAddress, DisplayName, Subject, DisplayMsg, AttachmentPath, ImagePath, ImageHeight, ImageWidth)
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
template = FindTemplate()
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(0)
With objOutlookMsg
' Add the To recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add(EmailAddress)
objOutlookRecip.resolve
objOutlookRecip.Type = 1
' Set the Subject, Body, and Importance of the message.
.Subject = Subject
.bodyformat = 3
.Importance = 2 'High importance
body = Replace(template, "{First}", name)
body = Replace(body, "{the}", the)
if not isNull(ImagePath) then
if not ImagePath = "" then
.Attachments.add ImagePath
image = split(ImagePath,"\")(ubound(split(ImagePath,"\")))
body = Replace(body, "{image}", "<img src='cid:" & image & _
"'" & " height=" & ImageHeight &" width=" & ImageWidth & ">")
end if
else
body = Replace(body, "{image}", "")
end if
if not isNull(AttachMentPath) then
.Attachments.add AttachmentPath
end if
.HTMLBody = body
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Function FindTemplate()
Set OL = GetObject("", "Outlook.Application")
set Drafts = OL.GetNamespace("MAPI").GetDefaultFolder(16)
Set oItems = Drafts.Items
For Each Draft In oItems
If Draft.subject = "Template" Then
FindTemplate = Draft.HTMLBody
Exit Function
End If
Next
End Function
It works fine when run off my local machine, but when run off Windows server it throws out an error at the line:
Set wb = app.Workbooks.Open("Y:\Billing_Common\autoemail\*.xls")
Saying it cannot find the file specified, the server has Office 2003 on it and I have ran out of ideas on why it's not working.
Any help would be much appreciated!
Thanks.
Most likely the Open method of Office 2003 doesn't support wildcards in the path. You'll have to enumerate the files in that folder:
Set app = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("Y:\Billing_Common\autoemail").Files
If LCase(fso.GetExtensionName(f)) = "xls" Then
Set wb = app.Workbooks.Open(f.Path)
...
wb.Close
End If
Next

Resources