दोनों फ़ंक्शन मापदंडों को मान्य करने की कोशिश करें, और लौटी हुई वस्तु की जांच करें Nothing
शीर्ष Sub
एक परीक्षा है, जिसमें दर्शाया गया है कि रिटर्न प्रकार कैसे जांचेंFunction
Option Explicit
Public Sub TestPart()
Dim result As Range
Set result = FindPartNumber(123, ThisWorkbook) 'Make sure that "result" is Set
If Not result Is Nothing Then Debug.Print result.Address 'Check result object
End Sub
'If String/Workbook params are missing, or part is not found, this returns "Nothing"
Public Function FindPartNumber(ByVal part As String, ByVal mplWb As Workbook) As Range
Dim findRow As Range, ws As Worksheet
If mplWb Is Nothing Or Len(part) = 0 Then Exit Function 'Invalid file (mplWb)
With mplWb
On Error Resume Next 'Expected error: sheet name not found (sheet doesn't exist)
Set ws = .Worksheets("Item Master")
If Not ws Is Nothing Then
With ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
Set findRow = .Find(What:=part, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
MatchCase:=True)
If Not findRow Is Nothing Then Set FindPartNumber = findRow
End With
End If
End With
End Function
।
ध्यान दें
फ़ंक्शन को अधिक सामान्य (पुन: प्रयोज्य) बनाने के लिए, सभी हार्ड-कोडेड भागों को बाहर स्थानांतरित करें
Option Explicit
Public Sub TestPart()
Dim ws As Worksheet, result As Range, searchRange As Range
Set ws = ThisWorkbook.Worksheets("Item Master")
Set searchRange = ws.Range("A1:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
Set result = FindPartNumber(123, searchRange)
If Not result Is Nothing Then Debug.Print result.Address
End Sub
'If String/Range params are missing, or part is not found, this returns "Nothing"
Public Function FindPartNumber(ByVal part As String, ByVal rng As Range) As Range
Dim findRow As Range
If rng Is Nothing Or Len(part) = 0 Then Exit Function 'Invalid search range or part
Set findRow = rng.Find(What:=part, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
MatchCase:=True)
If Not findRow Is Nothing Then Set FindPartNumber = findRow
End Function