语法(缺少运算符)在vba中使用runsql将字符串内容保存到变量时出错

pu82cl6c  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(549)

我正在尝试从文本框中提取选定的文本,并将字符串保存到表中。表中只有一行,其他变量( SelectionStart , SelectionLength )能够保存到表中而没有问题。
当它到达第三个runsql命令时,我得到一个错误:
运行时错误“3075”:查询表达式中存在语法错误(缺少运算符)
并以所选文本结束。

Sub ArticleTextContentBox_Click()

Dim SelectionStart As String
Dim SelectionLength As String
Dim SelectionText As String

SelectionStart = [Forms]![1CodingArticlesForm]![ArticleTextContentBox].SelStart + 1
SelectionLength = [Forms]![1CodingArticlesForm]![ArticleTextContentBox].SelLength
SelectionText = Mid([Forms]![1CodingArticlesForm]![ArticleTextContentBox], SelectionStart, SelectionLength)

'Runs successfully, to show that SelectionText variable works correctly
MsgBox SelectionText

DoCmd.RunSQL "UPDATE TEMP_StringPosition SET TEMP_StringPosition.StartLocation = " & SelectionStart & ";"
DoCmd.RunSQL "UPDATE TEMP_StringPosition SET TEMP_StringPosition.StringLength = " & SelectionLength & ";"

'This is the line that causes the error:
DoCmd.RunSQL "UPDATE TEMP_StringPosition SET TEMP_StringPosition.ExtractedTextChunk = " & SelectionText & ";"

End Sub

我不确定我在这里遗漏了什么,因为前两个变量能够毫无问题地更新表

hgqdbh6s

hgqdbh6s1#

使用一条update语句保存所需的任意多个字段。如果字段是文本类型,请使用撇号分隔符(对于日期/时间,请使用#)。我更喜欢currentdb.execute来消除弹出警告。

CurrentDb.Execute "UPDATE TEMP_StringPosition SET StartLocation = " & SelectionStart & _ 
   ", StringLength = " & SelectionLength & ", ExtractedTextChunk = '" & SelectionText & "'"

sql将引号和撇号视为特殊字符。如果数据包含引号或撇号字符,一种处理方法是通过将字符加倍来“转义”字符,以便sql将它们作为普通文本接受。使用replace()函数: Replace(Replace(SelectionText, """", """" & """"), "'", "''") 或者如果这更容易理解: Replace(Replace(SelectionText, Chr(34), Chr(34) & Chr(34)), "'", "''") 另一种方法是使用嵌入参数。tempvars是在sql字符串中嵌入参数的一种方法。查看如何在microsoft access的不同上下文中使用vba中的参数?
另一种方法是打开一个记录集对象并使用编辑模式将字段设置为新值。

bz4sfanl

bz4sfanl2#

考虑将sql与vba完全分离的参数化,避免字符串串联和引号标点以及字符串中特殊字符的问题。ms access支持带有querydefs的参数。
sql(另存为查询对象)

PARAMETERS prm_loc INT, prm_len INT, prm_txt VARCHAR(255);
UPDATE TEMP_StringPosition sp 
SET sp.StartLocation   = [prm_loc]
    sp.StringLength    = [prm_len]
    ExtractedTextChunk = [prm_txt]

vba(参考以上查询)

Sub ArticleTextContentBox_Click()

    Dim SelectionStart, SelectionLength, SelectionText As String
    Dim qdef As QueryDef

    With [Forms]![1CodingArticlesForm]![ArticleTextContentBox]
         SelectionStart = .SelStart + 1
         SelectionLength = .SelLength
         SelectionText = Mid(.Value, SelectionStart, SelectionLength)
    End With

    'Runs successfully, to show that SelectionText variable works correctly
    MsgBox SelectionText

    Set qdef = CurrentDb.QueryDefs("mySavedUpdateQuery")

    ' BIND PARAMETERS
    qdef!prm_loc = SelectionStart
    qdef!prm_len = SelectionLength
    qdef!prm_txt = SelectionText

    ' RUN ACTION
    qdef.Execute dbFailOnError

    Set qdef = Nothing
  End Sub

相关问题