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

为什么.CopyFromRecordset从我的logging集输出中截断string?


我曾经多次使用.CopyFromRecordset但没有经历过这个问题,但由于某些原因,这个VBA代码导致我的string数据被截断。 我目前使用的代码如下:

当前代码

 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 Eg 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 Eg Limited JK&L AB1261 Final Example Company Limited 

我所试过的

SQL查询在我的SQLpipe理程序(HeidiSQL)中执行时工作正常 – 没有任何数据被截断。 更奇怪的是当我打开logging集后运行这段代码时:

 Debug.Print myRecSet.GetString 

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

附加信息

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

我明白了!

不知道如果你find自己的问题的答案是什么过程,但我在这里发布的答案,这有助于任何人或好奇的人…

从添加myRecSet到VBA上的监视列表,我注意到CursorLocation值被设置为adUseServer 。 虽然最初寻找一个决议我记得看到这通常设置为adUseClient而不是adUseServer

在打开logging集之前将CursorLocation值设置为adUseClient ,然后重新运行代码,结果是我的输出结果应该是没有截断的!

更改为我的代码:

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