将Excel值与SQL表If语句进行比较。

时间:2016-08-13 01:01:34

标签: mysql sql-server excel vba excel-vba

有没有办法可以使用VBA搜索SQL表,如果excel中的单元格包含SQL表中找到的相同数据,则返回Yes / No结果?

我在Excel工作表中有客户记录,我需要比较记录ID(A1)我需要逐个单元地比较'客户端'表,如果有匹配,如果是这样的话......如果值存在与否,我需要sql的某种输出。

实施例:  如果Cell.A1是= SQLTableA 然后'是' 其他 '无'

我觉得我很亲密,但是无法从sql获得正确的输出。

enter code here
Option Explicit
Dim cell As Range
Dim CustRow As Range

Const SQLConStr As String = "Driver={SQL Server} ;Server=<svrname>;Database=CustData; UID=user; PWD=<pass>"

Sub connectTODB()

Dim CustDataConn As ADODB.Connection
Dim CustDataCMD As ADODB.Command
Dim rs As ADODB.Recordset


Set CustDataConn = New ADODB.Connection
Set CustDataCMD = New ADODB.Command
Set rs = New ADODB.Recordset

CustDataConn.ConnectionString = SQLConStr
CustDataConn.Open
CustDataCMD.ActiveConnection = CustDataConn


Dim CustValue As String
CustValue = "ACP"


Dim strSQL As String
strSQL = "SELECT * FROM [CustData].[dbo].[CustomerData] WHERE (CustomerData.Client='" & CustValue & "')"



With rs
.ActiveConnection = CustDataConn
'open strsql

'.Open "IF EXISTS(SELECT * FROM [CustData].[dbo].[CustomerData] WHERE CustomerData.Client = 'ACA') Print 'Yes' Else Print 'No'" '(notworking)
'.Open "IF EXISTS(SELECT Client FROM CustData.dbo.CustomerData WHERE  CustomerData.Client = 'hdh') Print 'Yes' Else Print 'No'" '(notworking)
.Open "IF EXISTS(SELECT Client FROM CustData.dbo.CustomerData WHERE  CustomerData.Client = 'hdh')"

Workbooks("<file>.xlsm").Worksheets("CustOutput").Range("A2").CopyFromRecordset rs

.Close
End With

CustDataConn.Close
Set rs = Nothing
Set CustDataConn = Nothing


End Sub

2 个答案:

答案 0 :(得分:0)

您可以使用ADODB.Recordset.Filter属性返回匹配的记录。如果没有匹配的记录,则ADODB.Recordset.BOF将返回true。

With rs
    .ActiveConnection = CustDataConn
    .Open strSQL

    .Filter = "CustomerData.Client = 'ACA'"
    Debug.Print IIf(.BOF, "No", "Yes")

    .Filter = "CustomerData.Client = 'hdh'"
    Debug.Print IIf(.BOF, "No", "Yes")

    'Clear Filter
    .Filter = ""

    Workbooks("<file>.xlsm").Worksheets("CustOutput").Range("A2").CopyFromRecordset rs

    .Close
End With

答案 1 :(得分:0)

有人可以在这里检查我的理解......

这将打开连接并发送字符串,然后过滤我的值,过滤后.BOF将返回false,我将答案更改为“是/否”结果并将其输出到单元格... 。

之前我没有使用过BOF(EOF)值,微软的描述更难理解......但是......

如果BOF = True(则该值不存在&gt;更改为“No”)

如果BOF = False(那么该值确实存在&gt;更改为“是”)

所以..

enter code here

With rs

.ActiveConnection = CustDataConn
.Open strSQL
.Filter = "Client = 'ABC'"
Workbooks("file.xlsm").Worksheets("CustOutput").Range("A2") = IIf(.BOF, "No", "Yes")
.Close

End With