Search code examples
vbaexcelvlookupnamed-ranges

Setting Variable with VLookup & Named Ranges


I can not get the VLookup function to work when using a named range. I am sure it has something to do with how I am referencing "COA_Range" but cant find a solution that works

I have tried [], ([]), (""), [""],([""])......

(Below is an updated and expanded section of the code)

If Transaction_Type = 1 Then
    Debug.Print "Transaction Type :"; Transaction_Type
    Range("n10").Value = "Income"

    Debug.Print "COA # = "; TransactionInfo.Income_COA_Number.Value
    COA_Number = TransactionInfo.Income_COA_Number.Value
    Debug.Print COA_Number

    Range("n12").Value = TransactionInfo.Income_COA_Number.Value

    'thought from STACK OVERFLOW
    Debug.Print Range("COA_Range").Address()

    COA_1 = Application.WorksheetFunction.VLookup(COA_Number, Range("COA_Range"), 2, False)
    Debug.Print COA_1
    Range("n13").Value = COA_1

Solution

  • Special thanks to @jainashish, @Shai Rado for the thoughtful responses. I was able to pick up a few pointers from each.

    It was @Jeeped however who actually solved my problem. The "number" was being read as text and the CLng() expression worked for me. I have added my updated code below.

        If Transaction_Type = 1 Then
        Debug.Print "Transaction Type :"; Transaction_Type
            Range("n10").Value = "Income"
    
            'thought from STACKOVERFLOW
                'need to make sure that the number taken fromt the userform is ACTUALLY a number and not text that looks like a number
                    'use CLng to convert
    
        Debug.Print "COA # = "; CLng(TransactionInfo.Income_COA_Number.Value)
            COA_Number = CLng(TransactionInfo.Income_COA_Number.Value)
                Debug.Print "COA # = "; COA_Number
            Range("n12").Value = COA_Number
    
                'thought from STACK OVERFLOW
                    Debug.Print Range("COA_Range").Address()
                        'Yes the range is being found...
                            Dim COA_Range As Range
                            Set COA_Range = Range("COA_Range")
                                Debug.Print COA_Range.Address()
    
            COA_1 = WorksheetFunction.VLookup(COA_Number, Range("COA_Range"), 2, False)
                    Debug.Print COA_1
                        Range("n13").Value = COA_1
    
            COA_2 = WorksheetFunction.VLookup(COA_Number, Range("COA_Range"), 3, False)
                    Debug.Print COA_2
                        Range("n14").Value = COA_2
    
            COA_3 = WorksheetFunction.VLookup(COA_Number, Range("COA_Range"), 4, False)
                    Debug.Print COA_3
                        Range("n15").Value = COA_3
    
            COA_4 = WorksheetFunction.VLookup(COA_Number, Range("COA_Range"), 5, False)
                    Debug.Print COA_4
                        Range("n16").Value = COA_4enter code here