下面这段代码出现一个问题,就是在循环到第二次的时候报错为:"对象打开时,不允许操作",报错代码为"rs.LockType = adLockOptimistic"全部代码为:
Dim i As Integer
  Dim s As Integer
  s = txtqty - 1
  For i = 0 To s
  Dim strField1 As String
  Dim strField2 As String
  Dim strField3 As String
  Dim strSQL As String
  Dim cnn As New ADODB.Connection
  Dim rs As New ADODB.Recordset
    rs.LockType = adLockOptimistic
    rs.CursorType = adOpenKeyset
    cnn.CursorLocation = adUseClient
    cnn.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Showup.mdb"
    cnn.Open
    rs.Open "SELECT 型号,时间 FROM code where 型号='" & Text1.Text & "'", cnn
    If rs.EOF = False Then
      MsgBox "已经存在该数据."
    Else
        rs.AddNew
         With rs
            .Fields("型号") = Text1.Text
            .Fields("时间") = Text2.Text
            .Update
         End With
        MsgBox "保存成功"
       cnn.Close
    'begin print label
     Dim strLabelFile As String
    strLabelFile = App.Path & "\PUC.lad"
    If Dir(strLabelFile) = "" Then
       MsgBox "找不到文件!", vbOKOnly + vbInformation, "Prompt"
      Exit Sub
    End If
    Set oCSDoc = oCSApp.Documents.Open(strLabelFile)
    Set oCSVars = oCSDoc.Variables
    oCSVars.FormVariables("barcode").Value = Text1.Text
    oCSDoc.PrintLabel 1
    Text1.Text = oCSVars.FormVariables("barcode").Value
    oCSDoc.FormFeed
    oCSDoc.Close False
  'Text1.Text = ""
  End If
 Next i
谢谢了,急啊!

解决方案 »

  1.   

    不推荐使用 Dim ... As New,需要的时候 Set ... = New,用完就 Set ... = Nothing,如果你养成这个习惯就不会出这种问题。
      

  2.   

    ADODB.Connection对象只能打开一次,如果需要第二次打开必须先关闭。
      

  3.   

    很佩服写这段代码的人
    一个循环里面放那么多操作
    他还能理清楚建议:
    把那些变量定义以及打开关闭recordset等操作放到循环外面
    除非不得以
    也要用老鸟的方式也声明对象变量并及时set nothing
      

  4.   

    if  rs.state=adstateopen then rs.close
    rs.open 略..