Sub FindNumber()
Dim arrSeries()
Dim rngList As Range
Dim c As Long, e As Long, k As Long, r As Long
Dim StartNum As Long, LastNum As Long, FromNum As Long, ToNum As Long
e = Range("E" & Rows.Count).End(xlUp).Row
StartNum = Val(Range("E5").Value)
LastNum = Val(Range("E" & e).Value)
FromNum = Val(Range("C2").Value)
ToNum = Val(Range("C3").Value)
'Bay loi neu khong nhap tu so den so:
If FromNum + ToNum = 0 Then
MsgBox "Ban phai nhap tu so den so!"
Range("C2").Select
Exit Sub
End If
If FromNum = 0 And ToNum > 0 Then
MsgBox "Ban phai nhap tu so!"
Range("C2").Select
Exit Sub
End If
If FromNum > 0 And ToNum = 0 Then
MsgBox "Ban phai nhap den so!"
Range("C3").Select
Exit Sub
End If
'Dao lai so neu tu so lon hon den so
If FromNum > ToNum Then
Dim BigNum As String
BigNum = Range("C2").Value
Range("C2").Value = Range("C3").Value
Range("C3").Value = BigNum
FromNum = Val(Range("C2").Value)
ToNum = Val(Range("C3").Value)
End If
'Bay loi neu so ngoai danh sach co san (nho hon so dau hoac/va lon hon so cuoi)
If FromNum < StartNum Then
MsgBox "Ban phai nhap lai tu so!" & vbLf & "(Tu so nho hon so dau cua day so cho truoc!)"
Range("C2").ClearContents
Range("C2").Select
Exit Sub
End If
If ToNum > LastNum Then
MsgBox "Ban phai nhap lai den so!" & vbLf & "(Den so lon hon so cuoi cua day so cho truoc!)"
Range("C3").ClearContents
Range("C3").Select
Exit Sub
End If
e = Range("C" & Rows.Count).End(xlUp).Row
If e < 6 Then e = 6 Else e = e + 1
Set rngList = Range("C6:C" & e)
If FromNum = ToNum Then
k = Val(Range("C2").Value)
If WorksheetFunction.CountIf(rngList, k) = 0 Then
Range("C" & e).Value = Format(Range("C2").Value, "0000")
End If
Exit Sub
End If
ReDim arrSeries(1 To ToNum, 1 To 1)
For r = FromNum To ToNum
If WorksheetFunction.CountIf(rngList, r) = 0 Then
c = c + 1
arrSeries(c, 1) = Format(r, "0000")
End If
Next
If c > 0 Then
Range("C" & e).Resize(c).Value = arrSeries
End If
e = Range("C" & Rows.Count).End(xlUp).Row
Range("C6:C" & e).Sort Range("C6")
End Sub