我无法弄清楚我在VBA中使用CopyFromRecordset方法做错了什么。这是电子表格中的图片:
如您所见,所有列都未填充。这是我的代码的副本:
Private Sub btnRecherche_Click()
Dim rsRecherche As New ADODB.Recordset
Dim ws As New Worksheet
Set ws = Worksheets(11)
Select Case cmbRechercheType.Value
Case "offre"
If chk10der.Value = True Then
Set rsRecherche = getOffres(True)
ElseIf txtIDStart <> "" And txtIDEnd <> "" Then
Set rsRecherche = getOffres(False, CInt(txtIDStart.Text), CInt(txtIDEnd.Text))
Else 'Tout afficher
Set rsRecherche = getOffres
End If
Case "candidature"
If chk10der.Value = True Then
[...]
End If
End Select
If rsRecherche.Fields.Count > 0 Then
'On rentre les données dans les cellules
Range("Q13:AI660").ClearContents
For col = 0 To rsRecherche.Fields.Count - 1
ws.Cells(13, col + 17).Value = rsRecherche.Fields(col).Name
Next
ws.Range(ws.Cells(13, 17), ws.Cells(13, rsRecherche.Fields.Count)).Font.Bold = True
ws.Range("Q14:AI660").CopyFromRecordset rsRecherche 'That's where I use the CopyFromRecordset
End If
End Sub
调用数据库的函数(因为是的,我不使用Excel,也不使用Access作为我的数据库,但是HeidiSQL):
Public Function getOffres(Optional ByVal der As Boolean = False, Optional ByVal startID As Integer = -1, Optional ByVal endID As Integer = -1) As ADODB.Recordset
Dim sqlQuery As String
Set connect = New ADODB.Connection
connect.Open connString
Set rs = New ADODB.Recordset
If der Then
sqlQuery = "SELECT * FROM offre ORDER BY offre_ID desc LIMIT 10;"
ElseIf startID <> -1 And endID <> -1 Then
If startID > endID Then
MsgBox "La plage de numéro des enregistrements est incorrect !"
Exit Function
End If
sqlQuery = "SELECT * FROM offre WHERE offre_ID >= " & startID & " AND offre_ID <= " & endID & ";"
Else
sqlQuery = "SELECT * FROM offre INNER JOIN source ON offre.source_ID = source.source_ID;"
End If
rs.Open sqlQuery, connect
Set getOffres = rs
End Function
在最后一张图片中,代码进入了Else部分(我希望他)。
编辑:当我跨过这个时,我正在寻找答案:Record 256这是唯一一个返回所有数据的记录。我检查了数据库中其他条目的差异,但我找不到。
答案 0 :(得分:0)
我设法找到了解决方案(不使用CopyFromRecordset),这里是代码的副本:
If rsRecherche.Fields.Count > 0 Then
'On rentre les données dans les cellules
Range("Q13:AI660").ClearContents
For col = 0 To rsRecherche.Fields.Count - 1
ws.Cells(13, col + 17).Value = rsRecherche.Fields(col).Name
Next
ws.Range(ws.Cells(13, 17), ws.Cells(13, rsRecherche.Fields.Count)).Font.Bold = True
'ws.Range("Q14").CopyFromRecordset rsRecherche
row = 14
While Not (rsRecherche.EOF)
For fillCol = 0 To rsRecherche.Fields.Count - 1
ws.Cells(row, fillCol + 17).Value = rsRecherche.Fields.Item(fillCol)
Next
rsRecherche.MoveNext
row = row + 1
Wend
End If