Private Sub cmdExcel_Click()
On Error GoTo ErrorHandler
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strOrderDate As Date
Dim strAddress As String
Dim strCustomerName As String
Dim strWorksheetPath As String
Dim strTemplatePath As String
Dim bks As Excel.Workbooks
Dim wks As Excel.Worksheet
Dim strWorksheet As String
Dim appExcel As Object
Dim strsql As String
Dim intOrderID As Long
Dim strProductName As String
Dim dblUnitPrice As Double
Dim dblQuantity As Double
Dim dblDiscount As Double
Dim intRow As Integer
Set appExcel = GetObject(, "Excel.Application")
strTemplatePath = CurrentProject.Path & "\"
strWorksheet = "OrderDetails.xlt"
strWorksheetPath = strTemplatePath & strWorksheet
Set bks = appExcel.Workbooks
bks.Add strWorksheetPath
'Create variables for information to write to worksheet
strCustomerName = Me![CustomerID]
strAddress = Me![ShipCity] & Me![ShipAddress]
strOrderDate = Me![OrderDate]
Set wks = appExcel.ActiveSheet
'Write to cells in worksheet
With wks
.Range("C2").Value = strCustomerName
.Range("C3").Value = strAddress
.Range("C4").Value = strOrderDate
End With
'Use the ADO connection And Access data
Set cn = CurrentProject.AccessConnection
Set rs = New ADODB.Recordset
intOrderID = Me![OrderID]
strsql = " SELECT [Order Details].OrderID, Products.ProductName, [Order Details].UnitPrice, [Order Details].Quantity, [Order Details].Discount "
strsql = strsql & " FROM [Order Details] INNER JOIN Products ON [Order Details].ProductID = Products.ProductID "
strsql = strsql & " WHERE [Order Details].OrderID = " & intOrderID
With rs
Set .ActiveConnection = cn
.Source = strsql
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
intRow = 0
Do Until rs.EOF
strProductName = rs![ProductName]
dblUnitPrice = rs![UnitPrice]
dblQuantity = rs![Quantity]
dblDiscount = rs![Discount]
'Use Offset To Locate Cell
wks.Range("B7").Offset(intRow, 0).Value = strProductName
wks.Range("B7").Offset(intRow, 2).Value = dblQuantity
wks.Range("B7").Offset(intRow, 3).Value = dblDiscount
wks.Range("B7").Offset(intRow, 4).Value = dblUnitPrice
wks.Range("B7").Offset(intRow, 5).Value = dblUnitPrice * dblQuantity * (1 - dblDiscount)
intRow = intRow + 1
rs.MoveNext
Loop
'Make worksheet visible
appExcel.Application.Visible = True
Set rs = Nothing
ErrorHandlerExit:
Exit Sub
ErrorHandler:
If Err = 429 Then
'Excel is not running; open Excel with CreateObject
Set appExcel = CreateObject("Excel.Application.10")
Resume Next
Else
MsgBox "Error No: " & Err.Number & "; Description: " & Err.Description
Resume ErrorHandlerExit
End If
End Sub
[此贴子已经被作者于2003-12-25 0:48:35编辑过]
|