|
代码如下:我是要把Excel中的数据导到Table中。如果在执行 下面的代码的时候 有ERROR 就会跳转到ErrorHandler 并有 MsgBox Err.Description
然后如果我再一次执行的话 程序执行到 If rst.State = adStateOpen Then rst.Close 时就会报“下面这个错误,这是什么原因阿 ?
operation is not allowed in this context”
Public Sub ExcelInput(strwb As String, strws As String, strtable As String, strkey As String)
On Error GoTo ErrorHandler
Dim myData As String, myTable As String
Dim xlApp As New Excel.Application
Dim wb As Excel.Workbook
Dim ws As New Excel.WorkSheet
Dim myDataArrary As Variant
Dim strsql As String
Dim myDataArray As Variant
Dim i, j, n As Integer
Set wb = xlApp.Workbooks.Open(strwb)
Set ws = wb.Sheets(1)
myTable = strtable
With ws.Cells(1, 1).CurrentRegion
myDataArray = .Value
End With
Set Conn = CurrentProject.Connection
n = ws.Range("A65536").End(xlUp).Row
For i = 2 To n
strsql = "select * from " & myTable & " where " & strkey & "='" & ws.Cells(i, 1).Value & "'"
If rst.State = adStateOpen Then rst.Close
rst.Open strsql, Conn, adOpenKeyset, adLockOptimistic
If rst.RecordCount = 0 Then
rst.AddNew
For j = 1 To rst.Fields.count - 1
rst.Fields(j - 1) = myDataArray(i, j)
Next j
rst.Fields("updatedate") = Now
rst.Update
Else
For j = 1 To rst.Fields.count - 1
rst.Fields(j - 1) = myDataArray(i, j)
Next j
rst.Fields("updatedate") = Now
rst.Update
End If
Next i
MsgBox "数据保存完毕!"
If rst.State = adStateOpen Then rst.Close
Conn.Close
xlApp.Workbooks.Close
xlApp.Quit
Set wb = Nothing
Set ws = Nothing
Set rst = Nothing
Set Conn = Nothing
Exit Sub
ErrorHandler:
xlApp.Workbooks.Close
xlApp.Quit
MsgBox Err.Description
End Sub
|
|