我写了一个函数来查询数据库中的某些记录,我需要做的是能够过滤掉结果。我认为最简单的方法是在一个范围上使用.Find方法并设置单元格样式,然后根据样式进行过滤。我遇到的问题是由于某种原因我无法对细胞进行任何转换。我可以读取.Find结果值。 我该如何改变风格?
Public Function WoRecR(workOrders As Range)
Dim cell As Range
Dim cn As Object
Dim command As Object
Dim results As Object
Dim searchResult As Range
Dim field As Object
Dim criteria As String
Set cn = New ADODB.Connection
Set command = New ADODB.command
Set results = New ADODB.Recordset
criteria = ""
For Each cell In workOrders
If (Not IsEmpty(cell.Value)) Then
criteria = "DOCINDEX1='" & cell.Value & "' OR " & criteria
End If
Next cell
criteria = "(" & Left(criteria, Len(criteria) - 4) & ") "
With cn
.ConnectionString = "Provider=SQLOLEDB.1;" & _
"Persist Security Info=True;" & _
"Data Source=*********;" & _
"DATABASE=******;" & _
"UID=******;" & _
"PWD=******;"
.Open
End With
On Error GoTo CloseCon
command.ActiveConnection = cn
command.CommandText = "SELECT DOCINDEX1 FROM PVDM_DOCS_1_4 WHERE " & criteria & " AND DOCINDEX9!='Phone' " & _
"AND DATEDIFF(YEAR, GETDATE(), DOCINDEX10) > -2;"
command.CommandType = adCmdText
command.Execute
results.ActiveConnection = cn
results.Open command
While Not results.EOF
Set searchResult = workOrders.Find(What:=results.Fields(0).Value)
Debug.Print searchResult.Value
searchResult.Style = "Good"
results.MoveNext
Wend
cn.Close
CloseCon:
If Err.Number Then Debug.Print Err.Description
End Function
我所指的代码的确切部分是:
While Not results.EOF
Set searchResult = workOrders.Find(What:=results.Fields(0).Value)
Debug.Print searchResult.Value
searchResult.Style = "Good"
results.MoveNext
Wend
答案 0 :(得分:0)
您确定从.Find()
获得了结果吗?试试这个,确定:
While Not results.EOF
Set searchResult = workOrders.Find(What:=results.Fields(0).Value)
If Not searchResult is Nothing then
Debug.Print searchResult.Value
searchResult.Style = "Good"
Else
MsgBox ("nothing found") 'for debugging purposes only
End If
results.MoveNext
Wend