|
发表于 2013-4-24 20:16
|
显示全部楼层
本楼为最佳答案
上面有点小错误,变量名有个写错了。- Option Explicit
- Const adUseClient = 3
- Const adModeShareDenyWrite = 8
- Const adModeReadWrite = 3
- Dim StrConn$, strSQL$
- Dim AccessFile$, DataSource$
- Dim strError$
- Dim AdoConn As Object
- Dim AdoRst As Object
- Function ConnectDatabase() As Boolean
- AccessFile = "mg.mdb"
- DataSource = ThisWorkbook.Path & Application.PathSeparator & AccessFile
- StrConn = "Provider= Microsoft.Jet.OLEDB.4.0;" & _
- "Data Source=" & DataSource & ";"""
- If AdoConn Is Nothing Then
- Set AdoConn = CreateObject("ADODB.Connection")
- On Error GoTo ErrCheck
- With AdoConn
- .CommandTimeout = 5
- .ConnectionTimeout = 5
- .CursorLocation = adUseClient
- .Mode = adModeReadWrite 'adModeShareDenyWrite
- .ConnectionString = StrConn
- .Open
- End With
- ConnectDatabase = True
- Else
- ConnectDatabase = True
- End If
- Exit Function
- End1:
- Set AdoConn = Nothing
- Exit Function
- ErrCheck:
- strError = Err.Number & vbCrLf & _
- Err.Description
- Resume End1
- End Function
- Sub 用户更新()
- If Not ConnectDatabase Then
- MsgBox strError, vbCritical
- Exit Sub
- End If
- strSQL = "delete from yftab"
- AdoConn.Execute strSQL
- Set AdoRst = CreateObject("ADODB.Recordset")
- AdoRst.Open "yftab", AdoConn, 2, 3 'adOpenDynamic, adLockOptimistic
- Dim lLastRow&, i&, j&
- Dim arr
- lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
- If lLastRow < 3 Then Exit Sub
- arr = Range("a2:j" & lLastRow)
- arr(1, 1) = "gh"
- arr(1, 2) = "name"
- arr(1, 3) = "password"
- arr(1, 8) = "生产计划"
- Randomize (2013)
- With AdoRst
- For i = LBound(arr) + 1 To UBound(arr)
- .AddNew
- For j = 1 To UBound(arr, 2)
- .Fields(arr(1, j)).Value = arr(i, j)
- Next
- .Fields("id") = (Rnd(2013) * 65536 + 1) \ 1
- .Update
- Next
- End With
- Set AdoRst = Nothing
- MsgBox "用户更新完成", vbInformation + vbOKOnly
- End1:
- Exit Sub
- ErrCheck:
- MsgBox Err.Number & vbCrLf & _
- Err.Description, vbCritical
- Resume End1
- End Sub
- Sub 读取用户()
- If Not ConnectDatabase Then
- MsgBox strError, vbCritical
- Exit Sub
- End If
- On Error GoTo ErrCheck
- Dim lLastRow&
- Dim arr, strFields$
- lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
- If lLastRow < 2 Then Exit Sub
- arr = Range("a2:j" & lLastRow)
- If lLastRow > 2 Then Range("a3:j" & lLastRow).Value = ""
- arr(1, 1) = "gh"
- arr(1, 2) = "name"
- arr(1, 3) = "password"
- arr(1, 8) = "生产计划"
- arr = WorksheetFunction.Index(arr, 1, 0)
- strFields = Join(arr, ",")
- strSQL = "select "
- Range("a3").CopyFromRecordset AdoConn.Execute(strSQL & strFields & " from yftab")
- MsgBox "用户导入完成", vbInformation + vbOKOnly
- End1:
- Set AdoRst = Nothing
- Exit Sub
- ErrCheck:
- MsgBox Err.Number & vbCrLf & _
- Err.Description, vbCritical
- Resume End1
- End Sub
复制代码 |
|