Results 1 to 2 of 2

Thread: Declaring Variables in Excel VBA

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2015
    Posts
    1

    Declaring Variables in Excel VBA

    Hi All,

    I'm very new to VBA, I've had some experience with Matlab and wish Vba was as user friendly

    I'm starting off with basics such as declaring variables

    I've tried running this script I found from another forum, but can't seem to get the values of the variables to appear in the Locals or Watches window, any ideas?

    Thanks

    Code:
    Public intA As Integer
    Private intB As Integer
    
    Function AddSomeNumbers() As Integer
        intA = 2
        intB = 3
        AddSomeNumbers = intA + intB
    End Function
    Name:  variables.jpg
Views: 356
Size:  27.6 KB

  2. #2
    PowerPoster
    Join Date
    Dec 2004
    Posts
    24,965

    Re: Declaring Variables in Excel VBA

    the variables will only be in the locals window if you pause (breakpoint) the code while it is running, best for trial purpose, on the end function line, you can then see the final value of all variables

    in most cases you should dimension your variables in the least scope possible (rather than globally), the variables should be passed to your function then the result returned to the calling procedure (sub or function)
    Code:
    Sub test()
    Dim inta As Integer, intb As Integer
    inta = 3
    intb = 11
    MsgBox addsumnumbers(inta, intb)
    End Sub
    
    Function addsumnumbers(numa As Integer, numb As Integer, Optional numc As Integer, Optional numd As Integer) As Long
    addsumnumbers = numa + numb + numc + numd
    End Function

    better to post vba questions in Office development forum
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

Posting Permissions

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



Click Here to Expand Forum to Full Width