gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:33:13 24 4
gpt4 key购买 nike

如果 excel 中的单元格包含在 SQL 表中找到的相同数据,有没有一种方法可以使用 VBA 搜索 SQL 表并返回是/否结果?

我在 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

最佳答案

您可以使用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

关于mysql - 将 Excel 值与 SQL 表 If 语句进行比较。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38928216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com