• Declaring variables (VBA/Excel/2000)

    Author
    Topic
    #417288

    Confused again
    I am calling a procedure in module B several times from Module A,

    Module A appears in total below.
    ~~~~~~~~~~~~~~~~~~~~~Module A~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Dim ssubdirlst() As String
    Dim sFileDir() As String
    Dim sFileNames() As String
    Dim dFileDateTime() As Date
    Public Sub test()
        Call SearchDirectory.SearchDirectory("C:My Documents", _
        False, False, ssubdirlst(), sFileDir(), sFileNames(), dFileDateTime())
        Call SearchDirectory.SearchDirectory("C:My Documents", _
        False, False, ssubdirlst(), sFileDir(), sFileNames(), dFileDateTime())
        Call SearchDirectory.SearchDirectory("C:My Documents", _
        False, False, ssubdirlst(), sFileDir(), sFileNames(), dFileDateTime())
    End Sub
    

    The Declarations of Module B appear below.
    ~~~~~~~~~~~~~~~~~~~~~Module B~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Option Explicit
    Dim lFileCount As Long
    Dim mstrRoot As String
    Dim lSubDirCount As Long
    
    Public Sub SearchDirectory(spath As String, JustTopLevel As Boolean, _
        JustDirs As Boolean, sSubDirList() As String, sFileDir() As String, _
        sFileNames() As String, dFileDateTime() As Date)     
    

    Can someone please explain why lFileCount is not reset to 0 on the second and third instance of SearchDirectory being called?

    Viewing 1 reply thread
    Author
    Replies
    • #935866

      You have declared lFilecount at the Module B level. It will keep its value while Module B is loaded, and will only be reset to 0 if you do so explicitly. In particular, it will retain its value between runs of SearchDirectory.

      If you want lFileCount to be reset each time you call SearchDirectory, you must either do so at the beginning of the procedure:

      Dim lFileCount As Long

      Public Sub SearchDirectory(…)
      lFileCount = 0

      or you must declare lFileCount within the procedure. It will then be initialized to 0 automatically each time you call SearchDirectory:

      Public Sub SearchDirectory(…)
      Dim lFileCount As Long

      • #935868

        Thank you Hans and Legare
        I like to believe that the more I interact with you gentlemen, the less dumb I get.

    • #935867

      Because it is declared (DIMentioned) outside a procedure. This makes it a global variable that is not reset.

    Viewing 1 reply thread
    Reply To: Declaring variables (VBA/Excel/2000)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: