mercredi 16 janvier 2019

VBA - How to write two IF statements for different ranges in a loop

I'll make it very simple: I am working on an Excel document using VBA. This document contains a database with multiple columns, but for simplicity, let's say I have 2 columns: Column C corresponds to names and column F corresponds to numbers. I'm trying to create a macro that checks all the numbers in column F (with a loop). If the number is above 100, then check the adjacent cell in column C. If the name corresponds to a condition (let's say corresponds to John or Tom), then add the value of the number in another sheet. If none of those apply, check the next cell. My problem is that I can't find a way to define the cells in column C (Creating a variable/object to call the cells or calling directly the adjacent cell).

My code looks like this:

Sub Test1()


    Dim rngnumbers, rngnames, MultipleRange As Range

    Set rngnumbers = Sheet2.Range("F2:F999")    
    Set rngnames = Sheet2.Range("C2:C999")
    Set MultipleRange = Union(rngnumbers, rngnames)

        For Each numb In rngnumbers
            If numb.Value >= 100 Then
                    If Sheet2.Range("C2") = "John" Or Sheet2.Range("C2") = "Tom" Then '''The problem here is that it only looks at the cell C2 and not the adjacent cell
                        Sheet1.Range("I999").End(xlUp).Offset(1, 0).Value = numb.Value
                    Else
                    End If
            End If
        Next numb

End Sub

I tried modifying the line: 'If Sheet2.Range("C2") = "John" Or Sheet2.Range("C2") = "Tom" Then' to something like: 'newname.String = "John" ' But I can't find a way to define newname. Another idea would be to increment the If statement for the names withing the For loop.

Additional note: I am also not using formulas directly within Excel as I don't want any blank cells or zeros when the if functions are False.

Thank you for your help in advance!

Aucun commentaire:

Enregistrer un commentaire