If you write a new value to a variable, say by writing x = 2, the value at that memory location is changed. When you call that variable for use in calculations, the machine looks up the memory location and accesses that physical location to retrieve the value. There is a physical place on a RAM chip that stores the value of that variable, which is referenced by a memory location ID (memory address). In a nutshell, that’s what ByVal does.Īll computer programs must store their variables somewhere in working memory (RAM). The string goodbye is actually assigned to a second, short-lived instance of myString, which is erased after sub_sub2 ends. This happens because the instance of myString that is looked up by the Debug.Print line is the original variable. To do this, simply add ByVal in the declaration line of the called sub, like this:Īt the end of this subroutine, myString should output hello. You can shield your original variable by making a copy of it, then passing this copy to the new function/sub instead of passing the original variable. Often you don’t want to modify your original data, but you want to work with that data in another function or sub. Sometimes it can even be dangerous to the integrity of your application. It’s relatively intuitive, but not always useful. The variable myString went to sub_sub, was modified, and came back with a different value. If you run this, you should see goodbye in your Immediate window (press Ctrl + g to display the immediate window). We didn’t specify how we passed the variable, so it defaults to ByRef. In this example we passed the variable myString to the sub_sub subroutine. Print myString End Sub Sub sub_sub ( myString ) myString = "goodbye" End Sub Sub pass_variables_with_defaults () Dim myString As String myString = "hello" sub_sub myString Debug.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |