Consulting

Results 1 to 6 of 6

Thread: Variable question

  1. #1
    VBAX Tutor
    Joined
    Jun 2005
    Posts
    214
    Location

    Variable question

    Hi,

    [vba]Sub Vari()
    Dim A As Integer

    'initialize
    A = 1
    Sheets(1).Cells(1, 1) = "A"

    'output
    MsgBox A
    MsgBox Sheets(1).Cells(1, 1)

    End Sub
    [/vba]

    How to manipulate MsgBox Sheets(1).Cells(1, 1) to become 1 as answer?

  2. #2
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    I think this is the change that you are looking for
    [VBA]Sheets(1).Cells(1, 1) = A [/VBA]

    As you've seen, "A" is interpreted as the literal string A.
    A is interpreted as the value that you've assigned to the variable A

  3. #3
    VBAX Tutor
    Joined
    Jun 2005
    Posts
    214
    Location
    Yes you're right. But take a look at the next code:

    [vba]Sub vari()
    Dim A3 As Integer
    'initialize
    A3 = 3
    Sheets(1).Cells(1, 1) = "A" & 3
    'output
    MsgBox A3
    MsgBox Sheets(1).Cells(1, 1)
    End Sub
    [/vba]

    Isn't it possible to become 3 as an answer after msgbox sheets(1).cells(1,1)

  4. #4
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    You cant' use concatenation to create a string that will be interpreted as a variable. (i.e. the
    Sheets(1).Cells(1, 1) = "A" & 3
    is putting the string "A3" in the cell)

    To do somethign like that you would use an array

    [VBA]Sub vari()
    Dim A3(1 To 10 As Integer
    'initialize
    A(3) = 3
    Sheets(1).Cells(1, 1) = a(3)
    'output
    MsgBox A(3)
    MsgBox Sheets(1).Cells(1, 1)
    End Sub [/VBA]

  5. #5
    VBAX Tutor
    Joined
    Jun 2005
    Posts
    214
    Location
    Thanks Mike,

    This might be helpful.
    Actually, I used variables like A_20, A_201 etc. in my real sub.
    (Public const A_20 as integer = 20 or someting like that)

    Now i know that A_20 in cells(1,1) never yields 20 as resullt of
    msgbox cells(1,1). At least if A_20 in cells(1,1) is compoesed of "A_" & 20

  6. #6
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    You cannot reference variables indirectly as you are trying, but you can use arrays as Mike showed.
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •