首页 > 解决方案 > 在宏的查询中使用来自工作表的输入

问题描述

我正在尝试从“输入”文件中获取第 3 列的百分比列,并使用它对价格进行折扣并将该价格一一放入输出文件中的第 7 列。

我将 SQL 连接传递给一个函数,一个在数据库中查找信息的 UPC 值,然后是百分比值(一个 Double)作为输入。

但是,我不断收到错误“关键字百分比附近的语法不正确”。我尝试重命名百分比变量,并使用 Val() 函数(如您在代码中所见)。

如果我把 Val() 拿出来,我会得到一个类型不匹配的错误

基本上:我无法弄清楚如何在我的查询中使用“百分比”的输入,例如 0.10。

 For i = 1 To 381
     wrkb.Worksheets("Output").Cells(i + 1, 2).CopyFromRecordset extractInfo(cnn, wrkb.Worksheets("Input").Cells(i, 2).Value, Val(wrkb.Worksheets("Input").Cells(i, 3).Value))
Next i


Function extractInfo(cnn As ADODB.Connection, upc As String, percent As Double) As ADODB.Recordset

'Initializes variables

Dim rst As New ADODB.Recordset
Dim StrQuery As String

'The query to run, feed the UPC value you acquired to then get all the other variables
StrQuery = "SELECT 'N' as Division, zzeupcnr.style as Style, color_code as Color, ' ' as label_code, dimension as Dimension, ROUND((a_price * (1.00 - percent)), 2), ret_price " & _
        "FROM zzeupcnr JOIN zzxstylr " & _
        "ON zzeupcnr.style = zzxstylr.style " & _
        "WHERE upc = '" & upc & "'"

'Performs the actual query
rst.Open StrQuery, cnn

Set extractInfo = rst 'Stores result

标签: sqlvbaexcel

解决方案


percent在查询字符串中使用字符串。

如果要使用变量值,则需要这样做:

StrQuery = "SELECT 'N' as Division, zzeupcnr.style as Style, color_code as Color, ' ' as label_code, dimension as Dimension, ROUND((a_price * (1.00 - " & percent & ")), 2), ret_price " & _
        "FROM zzeupcnr JOIN zzxstylr " & _
        "ON zzeupcnr.style = zzxstylr.style " & _
        "WHERE upc = '" & upc & "'"

注意" & percent & "


推荐阅读