我的Excel VBA代码从MySQL数据库中选择值时,我遇到了一个非常奇怪的问题。我用以下几列构造了一个简单的数据库:


ID
名称




并假设具有以下条目:

01;泛;彼得纽约市
02; P;彼得纽约市

但是现在的问题是,如果我从表中选择*,则仅显示以下输出:

01; P;泛;纽约市
02; P;泛;纽约市

那意味着我只看到一个条目的最小长度.....这是怎么回事?在该任务的不同模块中,我确实有很随意的VBA代码:

公共变量:

Public cn As ADODB.Connection
Public rs As ADODB.Recordset
Public strSql As String


连接模块:

Public Function connectDB()
Dim strServer_Name As String
Dim strDB_Name As String
Dim strUser_ID As String
Dim strPassword As String

With Sheet2
    strServer_Name = .Range("B2").Value
    strDB_Name = .Range("B3").Value
    strUser_ID = .Range("B4").Value
    strPassword = .Range("B5").Value
End With

Set cn = New ADODB.Connection

cn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" & _
";SERVER=" & strServer_Name & _
";DATABASE=" & strDB_Name & _
";UID=" & strUser_ID & _
";PWD=" & strPassword & ""
End Function


子模块:

Sub request()
strSql = "SELECT * FROM test"

Call connectDB
Set rs = New ADODB.Recordset
rs.Open strSql, cn, adOpenDynamic

With Sheet1.Range("A1")
    .ClearContents
    .CopyFromRecordset rs
End With

Call disconnectDB
End Sub


这是VBA问题,还是MySQL中有任何错误?

最佳答案

好的,我在这篇文章中找到了一个解决方案:sql-query-doesnt-return-full-results-for-only-one-field

以与其他人相同的方式解决该问题。在我的代码中,它看起来像这样:

Sub request()
Dim iCols As Integer
Dim iRows As Integer

strSql = "SELECT * FROM test"

Call connectDB
Set rs = New ADODB.Recordset
rs.Open strSql, cn, adOpenDynamic

iRows = 10

While Not rs.EOF
    For iCols = 0 To rs.Fields.Count - 1
        Tabelle1.Cells(iRows, iCols + 1).Value = rs.Fields(iCols).Value
    Next
    rs.MoveNext
    iRows = iRows + 1
Wend

Call disconnectDB
End Sub


但是感谢所有试图帮助我的人!

09-04 11:59
查看更多