如何将变量放在vba中的like语句中?

时间:2017-10-20 14:39:50

标签: sql excel-vba vba excel

我正在尝试使用sql语句从db访问中获取数据与变量

一样

变量是一个字符串“mrcTrx”

在评论中转到*******以直截了当。

我知道这不是什么大不了但我找不到答案谢谢你!

其余的代码很好,如果我为例子'05'设置一个值代码完美无缺

Sub GetMun()

          Dim cn As Object
          Dim rs As Object
          Dim intColIndex As Integer

          Dim TargetRange As Range
          Dim mrcMun As String
          Dim mrcTrx As String
          Dim reg As String

          mrcTrx = Val(Range("D2").Value)

            If Len(mrcTrx) < 2 Then

                mrcTrx = "0" + mrcTrx

            End If



            Debug.Print mrcTrx

          Dim totalGP As Integer
          Dim debutRng As String

          totalGP = Sheets("T1").Range("G247").Value

          debutRng = "D" & 250 + totalGP


        mrcMun = "D:\FicheMacro\Mun\PréparationTRX par Munic.mdb"

        'On Error GoTo ErrorGetGPmun

        Application.ScreenUpdating = False

        Set TargetRange = Sheets("T1").Range(debutRng)

        Set cn = CreateObject("ADODB.Connection")
        cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & mrcMun
'*******
       Set rs = CreateObject("ADODB.Recordset")
        rs.Open "SELECT MUNIC FROM Munic_en_MAJ_par_MRC WHERE MRC LIKE ' & mrcTrx & ' ", cn, , , adCmdText


            TargetRange.CopyFromRecordset rs



      Application.ScreenUpdating = True


     rs.Close
    Set rs = Nothing
     cn.Close
     Set cn = Nothing

   Exit Sub



ErrorGetGPmun:

    MsgBox "Valider le type de trx et l'entête de la T1", vbExclamation, "La Fiche! GP"


End Sub

1 个答案:

答案 0 :(得分:1)

您的语法不正确

"SELECT MUNIC FROM Munic_en_MAJ_par_MRC WHERE MRC LIKE '" & mrcTrx & "'"

将变量放入字符串时,请确保在语法中正确使用"&