我的项目的一个方面涉及将操作员输入的部件号与数据库中的列中的预定部件号列表进行比较。现在,我的程序告诉我在电子表格(50+)中输入的每个部件号与数据库中的任何部件号都不匹配,我已经验证这是错误的。我已经检查过电子表格部件号和数据库部件号都是字符串数据类型。我已经仔细检查过我的循环逻辑是好的,对我而言似乎应该有效。据我所知,数据库单元格或电子表格单元格中没有隐藏的字符。关于为什么我的程序没有检测到电子表格和数据库之间的任何匹配,我完全难过了。下面是Sub,其中包含用于检查零件号匹配的代码:
Sub CheckPN()
'Connect to the E2 database
Call SetPNConnection
'Open a recordset
Set PNRecordset = New ADODB.Recordset
PNRecordset.Open "EstimRpt", PNConnection, adOpenKeyset, adLockOptimistic, adCmdTable
PNSQLCmd = "SELECT DISTINCT [PartNo] FROM EstimRpt;"
'Loop through data, comparing part numbers to E2 database part number records
TotalBadPNCount = 0
With PNRecordset
For DataRowCount = 2 To TrackingLastRow
PNCount = 0
Part_Number = Tracking.Sheets("Operator Data").Range("A" & DataRowCount).Value
'MsgBox "The datatype for " & Part_Number & " is " & VarType(Part_Number) & "."
Do Until .EOF
'MsgBox "The datatype for " & .Fields("PartNo").Value & " is " & VarType(.Fields("PartNo").Value) & "."
If Part_Number = .Fields("PartNo").Value Then
'If .Fields("PartNo").Value = Part_Number Then
MsgBox Part_Number & " is a match."
PNCount = PNCount + 1
End If
.MoveNext
Loop
If PNCount < 1 Then
MsgBox "The P/N " & Part_Number & " entered in cell A" & DataRowCount & " is incorrect. Please correctly enter the P/N and re-run the program."
TotalBadPNCount = TotalBadPNCount + 1
End If
Next DataRowCount
If TotalBadPNCount >= 1 Then
Exit Sub
End If
End With
PNRecordset.Close
Set PNRecordset = Nothing
PNConnection.Close
Set PNConnection = Nothing
End Sub
另外,如果零件编号不匹配,我希望整个程序停止执行,而不仅仅是直接子程序。目前,只有这个子出口没有零件编号匹配。
感谢您对这两个问题的帮助。
约旦
答案 0 :(得分:0)
我建议不要使用循环来比较用户提交的数据集中的记录到永久表。而是将用户提交的数据集加载到数据库中的临时表中,并使用SQL来比较这两个表。
您可以尝试以下几点:
'Load spreadsheet into temp table
<your code here>
'open recordset in order to compare PartNos
Dim db As Database
Set db = CurrentDb
Dim rs As Recordset
sSQL = "select count(*) as [count] from temp " _
& " where temp.PartNo not in (select distinct EstimRpt.PartNo from EstimRpt)"
Set rs = db.OpenRecordset(sSQL)
ctRecords = rs![Count]
'if records are found in temp table that do not exist
'in the perm table, then end execution of everything.
if ctRecords > 0 then
End
else
'run the rest of your code
<your code here>
end if
'Drop temp table
<your code here>
答案 1 :(得分:0)
我终于找到了问题。数据库和电子表格之间的比较记录现在可以正常工作。我必须对我的代码进行以下更改:
而不是:
Do Until .EOF
我需要:
Do Until .EOF = True
我还需要在For循环声明之后添加以下内容:
.MoveFirst
现在我的代码正确循环。