【问题标题】:Excel VBA's SQLExcel VBA SQL
【发布时间】:2017-10-11 11:35:01
【问题描述】:

在我的 excel VBA 函数中,'strSQL' 帮助我获得完美的结果,以防所有数据字段(下)中所有记录的文本长度为 255 字符,否则如果该特定字段中的任何单元格,该函数将为所有记录返回空值包含超过 255 个字符。

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

我正在使用 ADODB 建立连接。

【问题讨论】:

  • 您有问题吗?
  • 没有问题,没有上下文很难回答
  • 很抱歉给您带来了困惑。问题是,如果源位置中的单个单元格的文本值长度大于 255 个字符,为什么 Recordset 会为所有记录返回空字段值,我该如何解决这个问题?
  • 您是否正在从 MS Access 数据库中检索记录? (如果是这样,请更正标签 - [access] 与 MS Access 无关 - 使用 [ms-access] 标签。)或者您是否从另一个 Excel 电子表格中检索数据? (当我看到以$ 结尾的表名时,我通常会想到这个。)

标签: sql excel vba ms-access


【解决方案1】:

您对查询结果做了什么?

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

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

【讨论】:

  • 数据存储在 Excel 中,我正在获取记录以将每个单元格的值发送到一些预定义的 PowerPoint 形状中。
  • 这可能是由于Excel中列的数据类型,我已经更新了我的答案。我同意其他 cmets 可能值得更清楚地表达您的问题
【解决方案2】:

这是将 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2021-09-10
    • 2023-03-17
    相关资源
    最近更新 更多