Excel VBA的SQL

Excel VBA的SQL

问题描述:

在我的excel VBA函数中,'strSQL'帮助我在所有数据字段中的所有记录的长度为255 char的情况下获得完美的结果,否则该函数返回所有记录的空值,该特定字段包含超过255个字符。Excel VBA的SQL

strSQL = "SELECT [Company Name], [ProfileType], [DataField0],[DataField1], 
      [DataField2],[DataField3],[DataField4],[DataField5],[DataField6],[DataField7] 
      FROM [Data$] WHERE [Company Name] = 'XYZ' ORDER BY [Heading_Order];" 

我使用ADODB建立连接。

+3

你有问题要问? – braX

+0

有没有问题,并没有上下文使这很难回复 –

+0

对不起,混淆。问题是,如果源位置中的单个单元格的文本值长度大于255 char,为什么Recordset将为所有记录返回空字段值,并且如何解决该问题? –

你对查询结果做了什么?

如果您尝试将它们插入到Access表中,请检查该表的数据类型以确保它不是Text字段。这有255个字符的限制。 对于较大的文本字段使用Memo(或Long Text

比这个数据可能会被截断为255个字符,如果其他的前8个的记录包含255个或更少的字符。默认情况下,Microsoft Excel ODBC驱动程序将扫描数据的前8行以确定每列中的数据类型。尝试将列的数据类型转换为文本(或者甚至将具有超过255个字符的行移动到第一行)

+0

数据存储在Excel中,我正在获取记录以发送某些预定义PowerPoint形状中的每个单元格值。 –

+0

这可能是由于Excel中列的数据类型,我已经更新了我的答案。我同意其他意见,可能值得更清楚地说出你的问题 – Leroy

以下是将SQL字符串转换为VBA代码的好方法。

创建表单

表单只需要两个文本框和一个命令按钮。 SQL语句可能很长,因此您将文本框放在选项卡控件的不同页面上。

Create a new form (in design view.) 
    Add a tab control. 
    In the first page of the tab control, add a unbound text box. 
    Set its Name property to txtSql. 
    Increase its Height and Width so you can see many long lines at once. 
    In the second page of the tab control, add another unbound text box. 
    Name it txtVBA, and increase its height and width. 
    Above the tab control, add a command button. 
    Name it cmdSql2Vba. 
    Set its On Click property to [Event Procedure]. 
    Click the Build button (...) beside this property. 
    When Access opens the code window, set up the code like this: 

Private Sub cmdSql2Vba_Click() 
    Dim strSql As String 
    'Purpose: Convert a SQL statement into a string to paste into VBA code. 
    Const strcLineEnd = " "" & vbCrLf & _" & vbCrLf & """" 

    If IsNull(Me.txtSQL) Then 
     Beep 
    Else 
     strSql = Me.txtSQL 
     strSql = Replace(strSql, """", """""") 'Double up any quotes. 
     strSql = Replace(strSql, vbCrLf, strcLineEnd) 
     strSql = "strSql = """ & strSql & """" 
     Me.txtVBA = strSql 
     Me.txtVBA.SetFocus 
     RunCommand acCmdCopy 
    End If 
End Sub 


http://allenbrowne.com/ser-71.html