简体   繁体   中英

VBA - Check if cell value is in a column

I have 2 sheets on Excel.

Sheet 1 contains a list of ~500 universities, with their global rankings in column A and university names in column B

Sheet 2 contains a list of individuals' names in column A, their university in column B and their exam scores in column C.

I would like to write a VBA code that checks sheet 2 if the individual's university is in the top 50 rank (in sheet 1, row 1 to row 50). If it is, I will multiply their score in column C by 1.15.

Thank you all in advance!

Try this (i did not check in live)

Sub checkUniversity()
Dim shInd As Worksheet
Dim rgInd As Range


Set shInd = Worksheets("Individuals")  ' put here name of your sheet

rgInd = shInd.Range("a1").CurrentRegion
lastR = rgInd.Rows.Count

With shInd
    For j = 2 To lastR ' assuming that row1 is header, and data starts in row2
    
        .Cells(j, 3).Value = .Cells(j, 3).Value * isTop50(.Cells(j, 2).Value)
    Next j
End With
End Sub

Function isTop50(university As String)
Dim shUniver As Worksheet
Set shUniver = Worksheets("universities")  'put here name of your sheet with universities
isTop50 = 1

For i = 2 To 51  '('2 is first row - 1st university, 51 row of 50th university)
    If shUniver.Cells(i, 2).Value = university Then
        isTop50 = 1.15
        Exit Function
    End If
Next i
End Function

after short time: why you want to do this with vba while you just have normal funcitons which you can use in eg column D of sheet individuals

=if(isna(vlookup(B2, [sheetUniversities]!B2:B51,1,0)), C2, C2*1.15)

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