Search code examples
excelvba

How do i get a Value from an Excel VBA cell?


This cant be that complicated, now can it? After reading for an hour, I still didnt find a working solution. I have a range _usage in a worksheet defs. I want to iterate thru the range's rows and output every first cell in the row.

Dim row As Range
Dim c As Range
For Each row In Worksheets("defs").Range("_usage").Rows
    c = row.Offset(0, 0)
    MsgBox "[" + CStr(c) + "]", , "Check"
Next row

Sadly in my different approaches I just get some weird errors (mismatching types without telling me what types it got and expected, undefined width-block-variable etc.)

How do I do this?


Solution

  • Try this code:

    Sub Test()
        Dim row As Range
        Dim c
        For Each row In Worksheets("defs").Range("_usage").Rows
            c = row(1).Value
            MsgBox "[" & c(1, 1) & "]", , "Check"
        Next row
    End Sub
    

    or

    Sub Test2()
        Dim row As Range
        For Each row In Worksheets("defs").Range("_usage").Rows
            MsgBox "[" & row.Cells(1).Value & "]", , "Check"
        Next row
    End Sub
    

    The second version is also good for single column case.