Option Explicit
Sub RecordSetFromSheet()
Dim rs As Object, rs2 As Object
Dim cn As Object, cmd As Object, j As Long
Dim s(1 To 2) As String, answered As Integer
Sheets("Documenti").Activate
Range("a2:g1000").ClearContents
Set rs = CreateObject("ADODB.Recordset")
Set rs2 = CreateObject("ADODB.Recordset")
Set cn = CreateObject("ADODB.Connection")
Set cmd = CreateObject("ADODB.Command")
'setup the connection
'[HDR=Yes] means the Field names are in the first row
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source='" & ThisWorkbook.FullName & "'; " & "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
.Open
End With
'setup the command
Set cmd.ActiveConnection = cn
cmd.CommandType = 1 'adCmdText
cmd.CommandText = "SELECT DISTINCT [numero di documento] & revisione AS unique_keys " & _
"FROM [Comment Sheets$] " & _
"ORDER BY [numero di documento] & revisione"
rs.CursorLocation = 3 'adUseClient
rs.CursorType = 2 'adOpenDynamic
rs.LockType = 3 'adLockOptimistic
rs2.CursorLocation = 3 'adUseClient
rs2.CursorType = 2 'adOpenDynamic
rs2.LockType = 3 'adLockOptimistic
'open the connection
rs.Open cmd
rs.movefirst
j = 1
While Not rs.EOF
If Not IsNull(rs("unique_keys")) Then
j = j + 1
cmd.CommandText = "SELECT * FROM [Comment Sheets$] WHERE [numero di documento] & revisione = '" & rs("unique_keys") & "'"
rs2.Open cmd
'rs2.Filter = "[numero di documento]='" & rs("numero di documento") & "' and revisione='" & rs("revisione") & "'"
rs2.movefirst
Cells(j, "A") = rs2("numero di documento")
Cells(j, "B") = rs2("revisione")
Cells(j, "C") = rs2.RecordCount
s(1) = "": s(2) = "": answered = 0
While Not rs2.EOF
s(1) = s(1) & rs2("Comment Sheets Code") & Chr(10) 'comment sheet code
s(2) = s(2) & rs2("Received date") & Chr(10) 'received date
If Trim(rs2("answer date")) <> "" Then answered = answered + 1
rs2.movenext
Wend
Cells(j, "D") = Left(s(1), Len(s(1)) - 1)
Cells(j, "E") = Left(s(2), Len(s(2)) - 1)
Cells(j, "F") = answered & " su " & rs2.RecordCount
Cells(j, "G") = IIf(answered = rs2.RecordCount, "YES", "NO")
rs.movenext
rs2.Close
Else
rs.movenext
End If
Wend
'disconnect the recordset
Set rs.ActiveConnection = Nothing
rs.Close
Set rs = Nothing
'cleanup
If CBool(cmd.State And 1) = True Then Set cmd = Nothing
If CBool(cn.State And 1) = True Then cn.Close
Set cn = Nothing
MsgBox "Done.", vbOKOnly + vbInformation, "Succesful"
End Sub
|