Is there a way I can use VBA to search a SQL table and return a Yes/No result if a cell in excel contains the same data found in a SQL table??
I have customer records in an Excel sheet where I need to compare the record id (A1) I need to compare cell by cell to the 'Client' table if there is a match, if so... I need some sort of output from sql if the value exists or not.
Example: If Cell.A1 is = SQLTableA then 'yes' else 'no'
I feel like I am close, but cant get the right output from 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
IF EXISTS(SELECT? If you're just wanting one value copied into one cell - you don't needcopyfromrecordset. Just get your connection string right, and the query working with the specific field you want back. Then assignrs!YourFieldNameto the cell