Excel 工作簿.Match找不到它应该找到的值
我有下面的函数将行添加到工作表中。在添加零件号之前,它会检查零件号是否存在。不幸的是,Match找不到现有数据,悄悄地添加了同一零件号的多个副本 有人能指出我遗漏了什么吗Excel 工作簿.Match找不到它应该找到的值,excel,vba,match,Excel,Vba,Match,我有下面的函数将行添加到工作表中。在添加零件号之前,它会检查零件号是否存在。不幸的是,Match找不到现有数据,悄悄地添加了同一零件号的多个副本 有人能指出我遗漏了什么吗 Private Sub OkButton_Click() Dim LastRow As Long LastRow = LastRowOnSheet("Parts List") Dim sht As Worksheet Set sht = Worksheets("Parts List")
Private Sub OkButton_Click()
Dim LastRow As Long
LastRow = LastRowOnSheet("Parts List")
Dim sht As Worksheet
Set sht = Worksheets("Parts List")
'Validate that the controls hold valid data
If Not (Me.PartNumberTextBox.Value Like "######") Then
MsgBox "Please enter a valid 6 digit Stackpole part number.", vbExclamation, "Invalid Part Number"
Me.PartNumberTextBox.SetFocus
Exit Sub
End If
If Me.DescriptionTextBox.Value = "" Then
MsgBox "Please enter a description for this part.", vbExclamation, "Description Required"
Me.DescriptionTextBox.SetFocus
Exit Sub
End If
'Validate that the part number does not already exist
On Error Resume Next
x = WorksheetFunction.Match(PartNumberTextBox.Value, sht.Range(sht.Cells(2, 3), sht.Cells(2, LastRow)), 0)
If Not (x = "") Then
x = x + 1
MsgBox ("Duplicate part number found at row: " & x)
Exit Sub
End If
'Add new row to the Parts List Sheet
With Worksheets("Parts List").Range("A1")
.Offset(LastRow, 0).Value = .Offset(LastRow - 1, 0).Value + 1
.Offset(LastRow, 1).Value = Me.DescriptionTextBox.Value
.Offset(LastRow, 2).Value = Me.PartNumberTextBox.Value
.Offset(LastRow, 3).Value = Me.StoresLocTextBox
End With
End Sub
我认为PartNumberTextBox.Value是字符串,但单元格值是整数。 将其转换为整数可以解决此问题
x = WorksheetFunction.Match(Int(PartNumberTextBox.Value), sht.Range(sht.Cells(2, 3), sht.Cells(2, LastRow)), 0)
它搜索错误的范围(行和列颠倒)
我确实尝试过使用CInt()。我试试这个,你走对了。我找到了另一个建议使用CLng()或Val()的线程,它很有效。我还有另一个输入错误:sht.Cells(2,LastRow)应该是sht.Cells(LastRow,2)。接受了,就像你让我走上正轨一样。再次感谢你的帮助。我大概和你在同一时间看到的。。再次感谢。
x = WorksheetFunction.Match(Int(PartNumberTextBox.Value), sht.Range(sht.Cells(2, 3), sht.Cells(LastRow, 3)), 0)