Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create Excel Spreadsheet with VBScript

Status
Not open for further replies.

RottPaws

Programmer
Mar 1, 2002
478
US
I am trying to export data from SQL Server into an Excel spreadsheet. I've got a DTS package that will dump the data into an existing spreadsheet, but I need to create the spreadsheet on the fly.

I've been able to find code that will create a text file and I found that if I name it as .xls, it will work. But I also need to add the column headings so I can dump data into it.

Here's the code I have for creating the file:
'Initialize file system object and file.
Dim fso
Dim a

'Create the text file.
Set fso = CreateObject("Scripting.FileSystemObject")
Set a = fso.CreateTextFile("C:\RPTS\gw_fallout.xls")

a.Close _________
Rott Paws

...It's not a bug. It's an undocumented feature!!!
 
dim xl,wb

set xl = createobject("Excel.Application")
set wb = xl.workbooks.add
wb.saveas "c:\boo.xls"

wb.close
xl.quit

set xl=nothing
set wb=nothing

you can then reference the newly created workbook
 
I think arst06d is right. I can't find any way for VBScript to create an Excel workbook besides automating the Excel.Application object.

You can even copy a recordset into a workbook after creating it like this through things such as:

Set xlSheet = wb.Worksheets(1)
xlSheet.Range("A1").CopyFromRecordset rs

Or you can play around to put in your header information using other objects and methods from Excel.Application.


The big problem is that a server normally doesn't have Excel installed. Even worse, I don't think this works in contexts that don't have a Windows station open (a desktop, visible or hidden). Worse still is that Office automation objects are not meant for concurrent (multiple user context) use in server code which probably would include your DTS package. MS has issued many dire-sounding warnings not to use Office automation objects in ASP pages for example.

Of course that never seems to stop people. If you don't have high scalability requirements and can handle the occasional server blue-screen or thread lockup, this will work.


So what's left? Well MS advises ADO:

Why Use ADO?

The use of ADO to transfer data to or retrieve data from an Excel workbook gives you, the developer, several advantages over Automation to Excel:
[ul][li]Performance. Microsoft Excel is an out-of-process ActiveX server. ADO runs in-process, and saves the overhead of costly out-of-process calls.
[li]Scalability. For Web applications, it is not always desirable to automate Microsoft Excel. ADO presents you with a more scaleable solution to handle data in a workbook.[/ul]
ADO can be used strictly to transfer raw data to a workbook. You cannot use ADO to apply formats or formulas to cells. However, you can transfer data to a workbook that is pre-formatted and the format is maintained. If you require "conditional" formatting after the data is inserted, you can accomplish this formatting with Automation or with a macro in the workbook.

Well cool! But wait a second. Like I said I can't find a way to create a workbook with headings like you need outside of Office automation objects.

One thing you could consider (assuming it met your needs) is to create an empty "template" workbook with just your headings. Then copy it using the FSO, and populate your data via ADO. Maybe this is where you were stuck in the 1st place?

If your workbooks (and worksheets in them) need to be created dynamically I don't have a good answer. If you can copy a standard blank workbook (only headings) and populate it, a simple script like this can do it (WSH example):
Code:
<job id = &quot;CreateXLS&quot;>
  <reference object = &quot;ADODB.Recordset&quot;/>
  <object id = &quot;objFSO&quot; progid = &quot;Scripting.FileSystemObject&quot;/>
  <object id = &quot;objMDBRS&quot; progid = &quot;ADODB.Recordset&quot;/>
  <object id = &quot;objXLSRS&quot; progid = &quot;ADODB.Recordset&quot;/>
  <script language=&quot;VBScript&quot;>
    Option Explicit
    Dim lngField

    'Copy the empty workbook as our new &quot;created&quot; workbook.
    objFSO.CopyFile &quot;WorkBook.xls&quot;, &quot;Created.xls&quot;, True


    'Get the data from the database table
    objMDBRS.Open &quot;Clients&quot;, _
                  &quot;Provider = Microsoft.Jet.OLEDB.4.0;&quot; _
                & &quot;Data Source = Source.mdb;&quot;, _
                  adOpenStatic, adLockReadOnly, adCmdTable

    'Open a recordset to our &quot;table&quot; in the workbook.
    objXLSRS.Open &quot;[Sheet1$]&quot;, _
                  &quot;Provider = Microsoft.Jet.OLEDB.4.0;&quot; _
                & &quot;Data Source = Created.xls;&quot; _
                & &quot;Extended Properties = 'Excel 8.0;Hdr=Yes'&quot;, _
                  adOpenKeyset, adLockOptimistic, adCmdTable

    'Copy the data.
    objMDBRS.MoveFirst
    Do While Not objMDBRS.EOF
      objXLSRS.AddNew
      For lngField = 0 To objMDBRS.Fields.Count - 1
        objXLSRS(lngField).Value = objMDBRS(lngField).Value
      Next
      objXLSRS.Update
      objMDBRS.MoveNext
    Loop

    'Close and finish.  WSH will clean up
    'objects defined using <object> elements.
    objMDBRS.Close
    objXLSRS.Close
    MsgBox &quot;Done!&quot;
  </script>
</job>
But alas, you probably had this part covered already.


Sorry.
 
For what it is worth column. Built the following VBScript app that runs on one of my servers to create an Excel spreadsheet based on ADO queries against an Access MDB.

To be sure the following code could be slimmed down, but this is simply a sample.

For what it is worth column.
DougCranston

'~~ScriptName~~. (rpthd.vbs)
'----------------------------------------------------
'~~Author~~. DCranston
'~~Prerequisites~~. VBScript 5.0
'~~Version~~. 1.0
'~~Date Created~~. 2/6/2003
'~~Version_History~~. Initial version
'~~Keywords~~. File exists, FileSystemObject
'~~Description~~. Test if a folder exists and creates one if not.
' Tests for file exists and deletes if exists.
' Creates an Excel spread, extracts data from
' Access MDB via ADO and DSN. Formats the spreadsheet
' saves File.
'-----------------------------------------------------
'~~Usage: rptHD [optional <startdate><enddate>
'~~[No Optional Arguments]: Generates report for last month.
'~~<startdate>: First day of month. Format mm/dd/yyyy
'~~<enddate>: Last day of month under report. Format mm/dd/yyyy
'========= Declarations =================
OPTION EXPLICIT

' Dimension variables
Dim dtFirstDayofLastMonth
Dim dtLastDayofLastMonth
Dim strFile
Dim strFilenm
Dim strfldr
Dim fndt
Dim i
dim strTxt
Dim rs1
Dim rs2
Dim sql
Dim sql1
Dim fldmax
Dim rowmax
Dim rowmax2
Dim iCol
Dim iRow2
Dim iRow
Dim recArray
Dim recCount
Dim result
dim strEndRptDt
dim strStrtRptDt
dim argsvalue
dim argtst

dim numerr
dim abouterr
dim errloc
dim strErrCd
dim errmessage
dim strErrLogFldr
dim strErrLogFn
dim strScriptNm
dim ii
dim strErrMsg
dim strErrTitle

dim dt
dim tdt
dim intDate
dim intDay
dim intMonth
dim intYear
dim oNewFldr
Dim oCn
dim oFilesys
Dim oWshell
Dim oArgs
Dim oXLApp
Dim oXLWb
Dim oXLWs
Dim oMessage
Dim oErrFile
Dim otxtstream
dim ecode


' Create Objects
Set oWShell = WScript.CreateObject(&quot;WScript.Shell&quot;)
Set oArgs = WScript.Arguments

' Assign Values to variables
strScriptNm = &quot;RPTHD&quot;
strFilenm = &quot;rpthd.xls&quot;
strFldr = &quot;c:\cmdfiles\tempfile&quot;
strFile = strFldr & &quot;\&quot; & strFilenm
strErrLogFldr = &quot;c:\cmdfiles\logs&quot;
strErrLogFn = &quot;rcerpthd.log&quot;

call CreateFnm

call CreateRpt


'---------------------------
' Functions and Subroutines
'---------------------------

Public Function CreateFnm()
' Set Error Handler
On Error Resume Next
argsvalue = oArgs.Count

If oArgs.Count = 0 Then
' Has no Args - assumes batch/cron run
' Call create directory routine
Call CreateDir()
' Call clearfile routine
Call ClearFile()
' Calculate start of past month and end of month
dtFirstDayofLastMonth = DateSerial(Year(Date), Month(Date) - 1, 1)
dtLastDayofLastMonth = DateSerial(Year(Date), Month(Date), 0)
set oArgs = nothing

ElseIf oArgs.Count = 2 Then
' Has two Command line arguments - For running other months reports
' Call create directory routine
Call CreateDir

' Test for valid date entered at command line
if isdate(oArgs.Item(0)) then
dtFirstDayofLastMonth = oArgs.Item(0)
Else
Err.Raise vbObjectError + 16 , ,&quot;CustomErr - Invalid date.&quot;
strErrCd = &quot;First date entered is not a valid date.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
end if

' Test for valid date entered at command line
if isdate(oArgs.Item(1)) then
dtLastDayofLastMonth = oArgs.Item(1)
else
Err.Raise vbObjectError + 16 , ,&quot;CustomErr - Invalid date.&quot;
strErrCd = &quot;Second date entered is not a valid date.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
end if

' Create filename based on date
tdt = cdate(dtLastDayofLastMonth)
fndt = show_date(tdt)
strFilenm = &quot;rce&quot; & fndt & &quot;.xls&quot;
set oArgs = nothing
Else
' If we got here we have incorrect # of commandline arguments.
set oArgs = nothing
strErrCd = &quot;Incorrect # of commandline arguments.&quot;
Err.Raise 450
call LogErrors(Err, strErrCd)
wscript.quit(1)
End If

' Assigns datebased filename to use to name spreadsheet.
CreateFnm=strFilenm
end Function


function show_date(dt)
' Function to convert date to mmyy with 0 padding
' Set Error Handler
On Error Resume Next
' Initialize local variables
intDate = dt
intDay = Day(intDate)
intMonth = Month(intDate)
intYear = Year(intDate)

'Get the day : parse method
if Len(intDay)=1 Then intDay = &quot;0&quot; & intDay

'Get the month : parse method
if Len(intMonth)=1 Then intMonth = &quot;0&quot; & intMonth

'get the year : parse method
if Len(intYear)=4 Then intYear = Right(intYear, 2)

show_date = intMonth & intYear

'Test for Error
If Err.Number <> 0 then
Err.Raise vbObjectError + 17 , ,&quot;CustomErr - Process failed.&quot;
strErrCd = &quot;Generated filename based on date process failed.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
End if

End function


Public Sub CreateDir()
' Test to see if Folder Exists and if not create it
' Set Error Handler
On Error Resume Next

' Test and create script output folder
Set oFilesys = CreateObject(&quot;Scripting.FileSystemObject&quot;)
If Not oFilesys.FolderExists(strFldr) Then
Set oNewFldr = oFilesys.CreateFolder(strFldr)
Set oNewFldr = Nothing
End If
' Test and create script ERROR LOG folder
If Not oFilesys.FolderExists(strErrLogFldr) Then
Set oNewFldr = oFilesys.CreateFolder(strErrLogFldr)
Set oNewFldr = Nothing
End If
set oFilesys = Nothing

'Test for Error
If Err.Number <> 0 then
Err.Raise vbObjectError + 18 , ,&quot;CustomErr - Create Dir failed.&quot;
strErrCd = &quot;Creating Subdirectory process failed.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
End if

End Sub


Public Sub ClearFile()
' Test if Old version of file exists delete it
' Set Error Handler
On Error Resume Next

Set oFilesys = CreateObject(&quot;Scripting.FileSystemObject&quot;)
if oFilesys.FileExists(strFile) then
oFilesys.DeleteFile(strFile)
end if
set oFilesys = Nothing

'Test for Error
If Err.Number <> 0 then
strErrCd = &quot;Creating Subdirectory process failed.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
End if

End Sub


Sub CreateRpt()
' Connect to the db with a DSN-less connection
' Set Error Handler
On Error Resume Next
' --- Create Instance of Connection Object ---
Set oCn = Wscript.CreateObject(&quot;ADODB.Connection&quot;)
oCn.Open &quot;DSN=rcerpt&quot; 'DC home
' oCn.Open &quot;DSN=rptrqst&quot; ' dc dsktop2000 ofc

' Create a server recordset object
Set rs1 = Wscript.CreateObject(&quot;ADODB.Recordset&quot;)

' Define Query to determine select criteria
sql1 = &quot;SELECT DISTINCT tblStores.txtRegion &quot;
sql1 = sql1 & &quot;FROM tblStores &quot;
sql1 = sql1 & &quot;ORDER BY tblStores.txtRegion;&quot;

' Execute the sql
rs1.Open sql1, oCn, 3, 3

'this opens a recordset with all unique names in Field
If Not rs1.EOF Then
rs1.MoveLast
rs1.movefirst
rowmax2 = rs1.RecordCount
End If

' Create an instance of Excel and add a workbook
Set oXLApp = CreateObject(&quot;Excel.Application&quot;)
'this required to determine recordcount
oXLApp.SheetsInNewWorkbook = rs1.RecordCount

'create a workbook with required sheets number
Set oXLWb = oXLApp.Workbooks.Add

'cycle thru sheets
For i = 1 To rowmax2
Set oXLWs = oXLWb.Worksheets(i)
oXLWs.Name = rs1.Fields(0).Value

' Create recordset obj
Set rs2 = Wscript.CreateObject(&quot;ADODB.Recordset&quot;)

' Define main query
sql = &quot;SELECT DISTINCTROW tblStores.txtStoreNo, &quot;
sql = sql & &quot;tblStores.txtStoreRCECd, tblStores.txtRegion, &quot;
sql = sql & &quot;tblStores.txtStoreName, &quot;
sql = sql & &quot;tblStores.txtState, &quot;
sql = sql & &quot;tblRequests.dtRqstSubmitted, &quot;
sql = sql & &quot;tblRequests.dtRptDate, tblRequests.txtRptType, &quot;
sql = sql & &quot;LCase([txtRequestor]), &quot;
sql = sql & &quot;tblRequests.txtBatchNo, &quot;
sql = sql & &quot;LCase([txtRqstReason])&quot;
sql = sql & &quot;FROM tblRequests INNER JOIN tblStores &quot;
sql = sql & &quot;ON tblRequests.txtStoreRCECd = tblStores.txtStoreRCECd &quot;
sql = sql & &quot;WHERE (((tblRequests.dtRqstSubmitted) Between #&quot; & dtFirstDayofLastMonth & &quot;# And #&quot; & dtLastDayofLastMonth & &quot;#)) &quot;
sql = sql & &quot;AND tblStores.txtRegion = '&quot; & rs1.Fields(0).Value & &quot;' &quot;
sql = sql & &quot;ORDER BY tblStores.txtRegion, &quot;
sql = sql & &quot;tblStores.txtStoreNo, &quot;
sql = sql & &quot;tblRequests.dtRqstSubmitted;&quot;

' Execute the sql
rs2.Open sql, oCn, 3, 3

' Call function to process request
Call TXLOut(sql, rs1.Fields(0).Value)
' Clean up Recordset
rs2.Close
Set rs2 = Nothing
' Next Record
rs1.movenext
Next 'i

' Close and set the recordset to nothing
rs1.Close
Set rs1 = Nothing

' Close and set the connection to nothing
oCn.Close
Set oCn = Nothing

' Save the spreadsheet as
oXLWb.SaveAs (strFldr & &quot;\&quot; & createFnm)
Set oXLWs = Nothing
oXLWb.Close False '/False to ignore changes '/ True to save changes
Set oXLWb = Nothing
oXLApp.Quit
Set oXLApp = Nothing
Set oFilesys = Nothing

' Send completed spreadsheet via email to assigned users
' Call sndfilemsg(dtFirstDayofLastMonth, dtLastDayofLastMonth, argsvalue)

'Test for Error
If Err.Number <> 0 then
strErrCd = &quot;Creating Report process failed.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
End if

End Sub


Public Function TXLOut(sql,sheet)
'Notice, that you need References to ADO
' Set Error Handler
On Error Resume Next

' Block display Excel and user control of Excel's lifetime
' FOR TESTING SET BOTH TO TRUE set to False to run scripted/crond
oXLApp.Visible = FALSE
oXLApp.UserControl = FALSE

' Test and address empty recordset
if rs2.BOF and rs2.EOF then
' Add Indication of records
oXLWs.Cells(2 , 9).Value = &quot;No Report Requests For This Time Period&quot;
With oXLWs.Range(&quot;I2&quot;)
.Interior.Color = RGB(196,196,196)
End With
Else

' Determine the array we are dealing with
If Not rs2.BOF And Not rs2.EOF Then
rs2.MoveFirst()
rs2.MoveLast()
rowmax = rs2.RecordCount + 1
fldmax = rs2.Fields.Count
End If

' Move to first record in recordset
rs2.movefirst

' Set counter for positioning data posting
iRow2 = 2

' Start a for/next loop that will end with the last record
For iRow = iRow2 To rowmax
For iCol = 1 To fldmax
If (rs2.Fields.Item(iCol - 1) = &quot;&quot;) Then
oXLWs.Cells(iRow, iCol).Value = &quot;&quot;
Else
oXLWs.Cells(iRow, iCol).Value = rs2.Fields(iCol - 1).Value
End If
Next
iRow2 = iRow2 + 1
' Move to the next record
rs2.movenext
Next
' Add Indication of records
oXLWs.Cells(rowmax + 1, 9).Value = &quot;Total Requests&quot;
oXLWs.Cells(rowmax + 1, 11).Value = rowmax - 1
' Set shading for column titles
With oXLWs.Range(&quot;A&quot; & rowmax +1 &&quot;:&quot; & PickCol(fldmax) & rowmax +1)
.Interior.Color = RGB(196,196,196)
End With
End If

' Set field names to the first row of the worksheet
oXLWs.Cells(1, 1).Value = &quot;Store#&quot;
oXLWs.Cells(1, 2).Value = &quot;Cd&quot;
oXLWs.Cells(1, 3).Value = &quot;Region&quot;
oXLWs.Cells(1, 4).Value = &quot;Store Name&quot;
oXLWs.Cells(1, 5).Value = &quot;State&quot;
oXLWs.Cells(1, 6).Value = &quot;Dt Sbmtd&quot;
oXLWs.Cells(1, 7).Value = &quot;Rprt Dt&quot;
oXLWs.Cells(1, 8).Value = &quot;Rpt Type&quot;
oXLWs.Cells(1, 9).Value = &quot;Requestor&quot;
oXLWs.Cells(1, 10).Value = &quot;Batch #&quot;
oXLWs.Cells(1, 11).Value = &quot;Reason&quot;

' Set Column Widths
oXLWs.Columns(1).ColumnWidth = 5.57
oXLWs.Columns(2).ColumnWidth = 5.57
oXLWs.Columns(3).ColumnWidth = 4
oXLWs.Columns(4).ColumnWidth = 19.75
oXLWs.Columns(5).ColumnWidth = 4
oXLWs.Columns(6).ColumnWidth = 9.3
oXLWs.Columns(7).ColumnWidth = 9.3
oXLWs.Columns(8).ColumnWidth = 8.3
oXLWs.Columns(9).ColumnWidth = 16.86
oXLWs.Columns(10).ColumnWidth = 5.57
oXLWs.Columns(11).ColumnWidth = 25

' Set first row as column titles over mult pages
With oXLWs.PageSetup
.PrintTitleRows = &quot;$1:$1&quot;
End With
oXLWs.PageSetup.PrintArea = &quot;&quot;

' Set Page header and footers, page margins, layout
oXLWs.PageSetup.PrintArea = &quot;&quot;
With oXLWs.PageSetup
.LeftHeader = &quot;&quot;
.CenterHeader = &quot;Reprint Requests by Region/Store#/Date Request Submitted for Period: &quot; & dtFirstDayofLastMonth & &quot;-&quot; & dtLastDayofLastMonth
.RightHeader = &quot;&quot;
.LeftFooter = &quot;&F&quot;
.CenterFooter = &quot;Page - &P&quot;
.RightFooter = &quot;&D &T&quot;
.LeftMargin = oXLApp.InchesToPoints(0.5)
.RightMargin = oXLApp.InchesToPoints(0.5)
.TopMargin = oXLApp.InchesToPoints(0.8)
.BottomMargin = oXLApp.InchesToPoints(0.8)
.HeaderMargin = oXLApp.InchesToPoints(0.5)
.FooterMargin = oXLApp.InchesToPoints(0.5)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = -4142
.Orientation = 2 ' landscape
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Draft = False
.PaperSize = 1 ' xlPaperLetter
.FirstPageNumber = 1 ' xlAutomatic
.Order = 1 ' xlDownThenOver
.BlackAndWhite = False
.Zoom = 100
End With

' Set formatting for entire sheet
' Addition of a + 1 is to include formatting for the report total line
' oXLWs.Range(&quot;A1:&quot; & PickCol(fldmax) & rowmax + 1).Select
oXLWs.Range(&quot;A1:&quot; & PickCol(fldmax) & rowmax + 1).Font.Name = &quot;Times New Roman&quot;
oXLWs.Range(&quot;A1:&quot; & PickCol(fldmax) & rowmax + 1).Font.Size = 8
oXLWs.Range(&quot;A1:&quot; & PickCol(fldmax) & rowmax + 1).Font.Bold = True
oXLWs.Range(&quot;A1:&quot; & PickCol(fldmax) & rowmax + 1).WrapText = True

' Set shading for column titles
With oXLWs.Range(&quot;A1:&quot; & PickCol(fldmax) & &quot;1&quot;)
.Interior.Color = RGB(196,196,196)
End With

' Set lines around cells
With oXLWs.Range(&quot;A1:&quot; & PickCol(fldmax) & rowmax)
with .Borders(7)
.LineStyle = 1
.Weight = 2
.Color = RGB(0,0,0)
end with
with .Borders(8)
.LineStyle = 1
.Weight = 2
.Color = RGB(0,0,0)
end with
with .Borders(9)
.LineStyle = 1
.Weight = 2
.Color = RGB(0,0,0)
end with
with .Borders(10)
.LineStyle = 1
.Weight = 2
.Color = RGB(0,0,0)
end with
with .Borders(11)
.LineStyle = 1
.Weight = 2
.Color = RGB(0,0,0)
end with
with .Borders(12)
.LineStyle = 1
.Weight = 2
.Color = RGB(0,0,0)
end with
End With

'Test for Error
If Err.Number <> 0 then
strErrCd = &quot;Creating Report process failed.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
End if

End Function


Function PickCol(fldmax)
' Translates cell column # to Alpha Char for cell ref
Select Case fldmax
Case 1
result = &quot;A&quot;
Case 2
result = &quot;B&quot;
Case 3
result = &quot;C&quot;
Case 4
result = &quot;D&quot;
Case 5
result = &quot;E&quot;
Case 6
result = &quot;F&quot;
Case 7
result = &quot;G&quot;
Case 8
result = &quot;H&quot;
Case 9
result = &quot;I&quot;
Case 10
result = &quot;J&quot;
Case 11
result = &quot;K&quot;
Case 12
result = &quot;L&quot;
Case 13
result = &quot;M&quot;
Case 14
result = &quot;N&quot;
Case 15
result = &quot;O&quot;
Case 16
result = &quot;P&quot;
Case 17
result = &quot;Q&quot;
Case 18
result = &quot;R&quot;
Case 19
result = &quot;S&quot;
End Select
PickCol = result
End Function


Function LogErrors(objErr,strErrCd)
' Function writes information to an Error log file and
' generates an email warning to server administrators
'
errloc = strErrCd
numerr = Err.Number
abouterr = Err.Description

strErrTitle = &quot;Error in: &quot; & strScriptNm & &quot; Error#: &quot; & numerr & &quot; Type: &quot; & abouterr
If numerr <> 0 Then

Set oErrFile = CreateObject(&quot;Scripting.FileSystemObject&quot;)
Set otxtstream = oErrFile.OpenTextFile(strErrLogFldr & &quot;\&quot; & strErrLogFn, 8, TRUE)

otxtstream.writeline(&quot;START Error log Page: &quot; & &quot; Date: &quot; & Now() & &quot; Err.Number: &quot; & Err.Number)

' Determine whether a VBS error has occurred and log it
If Err.Number <> 0 Then
' Report properties of VBScript Err object and write to logfile
otxtstream.writeline(&quot;VBScript Err Object:&quot;)
otxtstream.writeline(&quot;Err Occurred at: &quot; & strErrCd)
otxtstream.writeline(&quot;Number: &quot; & Err.Number)
otxtstream.writeline(&quot;Description: &quot; & Err.Description)
otxtstream.writeline(&quot;Source: &quot; & Err.Source)
otxtstream.writeline(&quot;HelpFile: &quot; & Err.HelpFile)
otxtstream.writeline(&quot;HelpContext: &quot; & Err.HelpContext)
' Report propertiesof VBScript Err object for emailing report
strErrTitle = &quot;Error in: &quot;& strScriptNm & &quot; Date: &quot; & Now() & &quot; Err.Number: &quot; & Err.Number
strErrMsg = &quot;VBScript Err Object:&quot; & vbcrlf
strErrMsg = strErrMsg & &quot;Err Occurred at: &quot; & strErrCd & vbcrlf
strErrMsg = strErrMsg & &quot;Number: &quot; & Err.Number & vbcrlf
strErrMsg = strErrMsg & &quot;Description: &quot; & Err.Description & vbcrlf
strErrMsg = strErrMsg & &quot;Source: &quot; & Err.Source & vbcrlf
strErrMsg = strErrMsg & &quot;HelpFile: &quot; & Err.HelpFile & vbcrlf
strErrMsg = strErrMsg & &quot;HelpContext: &quot; & Err.HelpContext & vbcrlf & vbcrlf

End if
End if

' Determine whether an ADO Error has occurred and log it
If IsObject(oCn) Then
If oCn.Errors.Count > 0 Then
For ii = 0 To oCn.Errors.Count - 1
' Report properties of ADO Error object.
otxtstream.writeline(&quot;ADO Error Object:&quot;)
otxtstream.writeline(&quot;Number: &quot; & oCn.Errors(ii).Number)
otxtstream.writeline(&quot;Description: &quot; & oCn.Errors(ii).Description)
otxtstream.writeline(&quot;Source: &quot; & oCn.Errors(ii).Source)
otxtstream.writeline(&quot;HelpFile: &quot; & oCn.Errors(ii).HelpFile)
otxtstream.writeline(&quot;HelpContext: &quot; & oCn.Errors(ii).HelpContext)
otxtstream.writeline(&quot;SQL State: &quot; & oCn.Errors(ii).SQLState)
otxtstream.writeline(&quot;NativeError: &quot; & oCn.Errors(ii).NativeError)
' End the range of the loop through all Error objects.
strErrMsg = strErrMsg & &quot;ADO Error Object:&quot; & vbcrlf
strErrMsg = strErrMsg & &quot;Number: &quot; & oCn.Errors(ii).Number & vbcrlf
strErrMsg = strErrMsg & &quot;Description: &quot; & oCn.Errors(ii).Description & vbcrlf
strErrMsg = strErrMsg & &quot;Source: &quot; & oCn.Errors(ii).Source & vbcrlf
strErrMsg = strErrMsg & &quot;HelpFile: &quot; & oCn.Errors(ii).HelpFile & vbcrlf
strErrMsg = strErrMsg & &quot;HelpContext: &quot; & oCn.Errors(ii).HelpContext & vbcrlf
strErrMsg = strErrMsg & &quot;SQL State: &quot; & oCn.Errors(ii).SQLState & vbcrlf
strErrMsg = strErrMsg & &quot;NativeError: &quot; & oCn.Errors(ii).NativeError & vbcrlf & vbcrlf

Next
End If
Set oCn = Nothing
End If
otxtstream.writeline(&quot;END Error log Page: &quot; & &quot; Date: &quot; & Now() & vbcrlf & vbcrlf)

' Send Error Message to System Administrators of Problem Encountered
' If used on WIN2 Server/WS remove the double ''
' and then comment out the CDONTS

' Sending a text email using a CDOSYS not CDONTS

Set oMessage = CreateObject(&quot;CDO.Message&quot;)

oMessage.From = &quot;fromuser@from.com&quot;
oMessage.To = &quot;touser@to.com&quot;
oMessage.Subject = strErrTitle & &quot; Scheduled Task&quot;
oMessage.Textbody = strErrMsg
oMessage.Configuration.Fields.Item _
(&quot; = 2
oMessage.Configuration.Fields.Item _
(&quot; = _
&quot;yoursmtpmailserver url&quot;
oMessage.Configuration.Fields.Item _
(&quot; = 25
oMessage.Configuration.Fields.Update
oMessage.Send
Set oMessage=Nothing

' CDONTS email for NT
' If using CDONTS remove double single quotes and comment out CDOSYS lines

'' set oMessage = CreateObject(&quot;CDONTS.NewMail&quot;)
'' oMessage.Subject = strErrTitle & &quot; Scheduled Task&quot;
'' oMessage.From = &quot;fromuser@from.com&quot;
'' oMessage.To = &quot;touser@to.com&quot;
'' oMessage.Cc = &quot;ccuser@cc.com&quot;
'' oMessage.Body = strErrMsg & VbCrLf
'' oMessage.Send
'' set oMessage=nothing

Wscript.Quit(1)
End Function


Public Function sndfilemsg(dtFirstDayofLastMonth, dtLastDayofLastMonth, argsvalue)
' Emails the report to the assigned personnel
' Set Error Handler
On Error Resume Next

strStrtRptDt = dtFirstDayofLastMonth
strEndRptDt = dtLastDayofLastMonth
argtst = cint(argsvalue)


If argtst = 0 then
' Send Error Message to System Administrators of Problem Encountered
' If used on WIN2 Server/WS remove the double ''
' and then comment out the CDONTS

' Sending a text email using a CDOSYS not CDONTS

Set oMessage = CreateObject(&quot;CDO.Message&quot;)

oMessage.From = &quot;fromuser@from.com&quot;
oMessage.To = &quot;touser@to.com&quot;
oMessage.Subject = &quot;Report Requests for: &quot; & strStrtRptDt & &quot;-&quot; & strEndRptDt
oMessage.AddAttachment &quot;c:\cmdfiles\tempfile\rcerpthd.xls&quot;
oMessage.TextBody = &quot;The attached Excel file contains last months Reprint Requests Summary.&quot; & VbCrLf
oMessage.Configuration.Fields.Item _
(&quot; = 2
oMessage.Configuration.Fields.Item _
(&quot; = _
&quot;yoursmtpmailaddress&quot;
oMessage.Configuration.Fields.Item _
(&quot; = 25
oMessage.Configuration.Fields.Update
oMessage.Send
Set oMessage=Nothing

' CDONTS email for NT
' If using CDONTS remove double single quotes and comment out CDOSYS lines

'wscript.echo strStrtRptDt
'wscript.echo strEndRptDt

'' set oMessage = CreateObject(&quot;CDONTS.NewMail&quot;)
'' oMessage.Subject = &quot;Report Requests for: &quot; & strStrtRptDt & &quot;-&quot; & strEndRptDt
'' oMessage.From = &quot;fromuser@verizon.com&quot;
'' oMessage.To = &quot;touser@to.com&quot;
'' oMessage.Cc = &quot;ccuser@ccuser.com&quot;
'' oMessage.AttachFile(&quot;c:\cmdfiles\tempfile\rcerpthd.xls&quot;)
'' oMessage.Body = &quot;The attached Excel file contains last months Reprint Requests Summary.&quot; & VbCrLf
'' oMessage.Send
'' set oMessage=nothing

End if

'Test for Error
If Err.Number <> 0 then
strErrCd = &quot;Creating Email distribution process failed.&quot;
call LogErrors(Err, strErrCd)
wscript.quit(1)
End if

End Function
 
Wow, now there's a script!

Still, too bad Jet can't create a workbook and add tables via ADOX the way you can an MDB (Access) database.
 
Via Jet would be the ultimate.

I am sure a real programmer would be able to slim down and make the sample script &quot;sing&quot;.. Just my best effort. Lots of room for improvement and experience.

DougCranston
 
Thanks for the scripts.

dilettante,
You were correct that I was stuck at creating a template. I need to dump the file to the local drive on the server. It seems strange, but I don't have direct access to create/copy a file to the server's local drive, but I could create a file and work with it through a script. It seems silly, but network permissions go that way sometimes .....

I'll try to work through these scripts and create the Excel file. In the meantime, I got it to work by dumping it to a csv file instead. _________
Rott Paws

...It's not a bug. It's an undocumented feature!!!
 
Rott Paws,
You should be able to handle this with DTS package alone.
1. create an empty spreadsheet on the server: c:\shared\test.xls (name the sheet within the test.xls so that you can reference it later letter call it DATA)

2. create an excel connection. the datasource should be Microsoft Excel 97-2000. The file name should be the full path and file name that you create in step 1 (c:\shared\test.xls)

3. use the Transform Data Task to pump the data into the excel connection. Of course, you configure the data pump such as source...when you click on the destination, select create new table and name your table the same name that you named the sheet in the test.xls (DATA). This should automatically create the data in the excel format sheet. If you run it everyday, you have to drop the DATA table and re-create it in order to get only new data in the sheet. Otherwise, the data will append onto what you already have in the sheet. Hope this is what you're looking for.
 
The problem I'm running into is in creating the file. When I am in design mode for the DTS package or when I execute it from Enterprise Manager, it works on my local workstation. So C:\RPTS\data.xls, for instance, is a file on my machine. I can create an empty file named data.xls on my local drive and the DTS package does exactly what I want it to do.

But when the DTS package is run automatically from a job, it uses the local drives of the server. I don't have direct access to create files on the server's hard drive. That's why I need the DTS package to create the file itself.

I'll keep playing around with it as time permits. I think the code above should help. In the mean-time, I've got it working using a txt (csv) destination document and I've been assigned some other priority stuff . . .

Thanks again for your help.

_________
Rott Paws

...It's not a bug. It's an undocumented feature!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top