gpt4 book ai didi

mysql - .CopyFromRecordset 正在截断粘贴到 Excel 中的数据

转载 作者:行者123 更新时间:2023-11-29 02:47:16 24 4
gpt4 key购买 nike

问题

为什么 .CopyFromRecordset 会从我的记录集输出中截断字符串?


我以前多次使用 .CopyFromRecordset 并没有遇到这个问题,但是由于某种原因,这个 VBA 代码导致我的字符串数据被截断。我目前使用的代码如下:

当前代码

Sub GetTable()

Dim myConnObj As ADODB.Connection
Dim myRecSet As ADODB.Recordset
Dim SQLStr As String
Dim eRow As Long

/*Open connection to database*/
Set myConnObj = CreateObject("ADODB.Connection")
myConnObj.Open _
"Driver={MySQL ODBC 5.3 ANSI Driver}; " & _
"Server=SERVERNAME; " & _
"Database=DATABASENAME; " & _
"Uid=ID; " & _
"Pwd=PASSWORD; " & _
"Option=3"

/* Set SQL string */
SQLStr = "SELECT t.field1, t.field2, t.field3, t.field4, t.field5, t.field6, NULL as field7 "
SQLStr = SQLStr & "FROM table AS t WHERE ISNULL(t.field4) AND NOT ISNULL(t.field5) GROUP BY t.field3;"

/* Open recordset */
Set myRecSet = CreateObject("ADODB.Recordset")
myRecSet.Open SQLStr, myConnObj, adOpenStatic

/* Set end row */
eRow = ThisWorkbook.Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

/* Clear current range */
ThisWorkbook.Sheets("Sheet1").Range("A2:G" & eRow).ClearContents

/* Copy data into worksheet */
ThisWorkbook.Sheets("Sheet1").Range("A2").CopyFromRecordset myRecSet

/* Close off objects */
Set myRecSet = Nothing
myConnObj.Close
Set myConnObj = Nothing

End Sub

当前输出

这段代码的输出如下所示:

provider_name     id              company_name
ABC AA1234 Example Limited
ABC AB1231 Another Example Limited
ABC AC1235 Another Company Example L
DEF AA1238 E.g. Limited
GF& AB1261 Final Example Company Lim

无论出于何种原因,每个单元格都会被填充,provider_name 被截断为 3 个字符,company_name 被截断为 25 个字符。

编辑:我省略了字段 4-7,因为这些字段的所有数据(正确)返回 NULL 值。

期望的输出

我的输出应该是这样的:

provider_name     id              company_name
ABC AA1234 Example Limited
ABCDEF AB1231 Another Example Limited
ABC AC1235 Another Company Example Ltd
DEFGHI AA1238 E.g. Limited
JK&L AB1261 Final Example Company Limited

我尝试过的

在我的 SQL 管理程序 (HeidiSQL) 中执行时,SQL 查询工作正常 - 没有数据被截断。更奇怪的是,当我打开记录集后运行这行代码时:

Debug.Print myRecSet.GetString

没有数据被截断!只有当我使用 .CopyFromRecordset 时,数据才会被截断。

附加信息

  • 我的实际 SQLStr 是 313 个字符长,因此拆分字符串。
  • 我的实际查询只产生 86 行和 7 列。
  • 最长的company_name是56个字符
  • 我的实际评论使用单引号 (') 进行评论,
    不是 /* */

最佳答案

通过将 myRecSet 添加到我在 VBA 上的监视列表,我注意到 CursorLocation 值设置为 adUseServer。我记得看到这通常设置为 adUseClient

在打开记录集之前将 CursorLocation 值设置为 adUseClient,然后重新运行代码使我的输出符合预期。

更改我的代码:

/* Open recordset */
Set myRecSet = CreateObject("ADODB.Recordset")
myRecSet.CursorLocation = adUseClient /* <--Added Code */
myRecSet.Open SQLStr, myConnObj, adOpenStatic

关于mysql - .CopyFromRecordset 正在截断粘贴到 Excel 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40361995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com