简体   繁体   中英

Excel if cell contain then write it in another

So basically I need to create list of number of lessons done by students in one cell ex.g (1,10,15,16). The maximum number of lessons is 50. Lesson is recognized by its number

What I want to do is to create a formula that shows all the lessons that arent done in another cell. I mean : In one cell i write lessons that student has accomplished for exemple 1,5,7, and in another cell the result would be automatically all numbers up to 50 except the one which are done so the cell would be 2,3,6,8....

I tried with

=ISNUMBER(SEARCH(substring,text))

but this doesnt give me good result.

To do this we ned to split the string on the , and then replace thos values with nothing.

This UDF does what you want:

Function LessonsLeft(rng As Range) As String
If rng.Count > 1 Then Exit Function
Dim spltStr() As String
Dim i As Long
spltStr = Split(rng.Value, ",")
LessonsLeft = ",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,"
For i = LBound(spltStr) To UBound(spltStr)
    LessonsLeft = Replace(LessonsLeft, "," & spltStr(i) & ",", ",")
Next i
LessonsLeft = Mid(LessonsLeft, 2, Len(LessonsLeft) - 2)
End Function

Put it in a module attached to the workbook then you would call it with a formula:

=LessonsLeft(A1)

在此输入图像描述

This is another option:

Function MissedLessons(str As String) As String
    Dim resultString As String
    Dim i As Integer

    str = "," & str & ","
    For i = 1 To 50
        If InStr(str, "," & i & ",") = 0 Then
            resultString = resultString & i & ","
        End If
    Next i  

    MissedLessons = Left(resultString, Len(resultString) - 1)
End Function

a little enhancement of Scott's solution:

  • let the user optionally specify the total number of lessons (default = 50)

  • avoid her to had code all lessons numbers string

as follows:

Function LessonsLeft(rng As Range, Optional nLessons As Long = 50) As String
    If rng.count > 1 Then Exit Function
    Dim spltStr() As String
    Dim i As Long

    With CreateObject("Scripting.Dictionary")
        For i = 1 To nLessons
            .Add i, i
        Next
        spltStr = Split(rng.Value, ",")
        For i = LBound(spltStr) To UBound(spltStr)
            .Remove CLng(spltStr(i))
        Next
        LessonsLeft = Join(.keys, ",")
    End With
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM