Page 1 of 2 12 LastLast
Results 1 to 10 of 20

Thread: Re: Defining multiple variables in VBA

  1. #1
    Junior Member
    Join Date
    Mar 2017
    Posts
    7
    Rep Power
    0

    Question Re: Defining multiple variables in VBA

    This is a carry over from Rick's post #18 in this MrExcel thread (I didn't want to derail the thread):

    Rick's post:

    Just so I can narrate, answer the first question with 5 and the second question with 9... the expected sum would be 14, not the 59 that is returned.

    Code:
    Sub Test()
      Dim S1, S2, S3 As Long
      S1 = InputBox("Enter first integer number:")
      S2 = InputBox("Enter second integer number:")
      S3 = S1 + S2
      MsgBox S3
    End Sub
    I've been using the format: Dim x, y, z as type for years now and have recently been shown the errors of my ways. But I never thought it caused any actual problems in my code until Rick posted the above.

    My question is this: I stepped thru the above code with watches on all the variables. It seems that Excel is assigning the non-explicitly declared variables as variants (expected) but then 'guessing' the type when they are assigned values. Do you have any idea what triggers the guess? I tried things like 5.0, 8.9 and the like to see if I can force the guess from String to Long or Double but the variables remained Variant/String types.

    Just curious, really. I may have to go back through all of my VBA to see what has actually been happening behind my back while I wasn't looking .

    Thanks,

    CJ


    https://www.youtube.com/watch?v=ySENWFIkL7c&lc=UgyqIYcMnsUQxO5CVyx4AaABAg


    https://www.youtube.com/watch?v=yVgLmj0aojI&lc=UgwWg8x2WxLSxxGsUP14AaABAg. 9k3ShckGnhv9k89LsaigoO
    https://www.youtube.com/watch?v=yVgLmj0aojI&lc=UgxxxIaK1pY8nNvx6JF4AaABAg. 9k-vfnj3ivI9k8B2r_uRa2
    https://www.youtube.com/watch?v=yVgLmj0aojI&lc=UgxKFXBNd6Pwvcp4Bsd4AaABAg
    https://www.youtube.com/watch?v=yVgLmj0aojI&lc=Ugw9X6QS09LuZdZpBHJ4AaABAg
    Last edited by DocAElstein; 07-09-2023 at 07:30 PM. Reason: Link didn't post...

  2. #2
    Senior Member
    Join Date
    Jun 2012
    Posts
    337
    Rep Power
    13
    What's the point ?
    The result of an Inputbox is always a string.

    Code:
    Sub M_snb()
      S1 = InputBox("Enter first integer number:")
        S2 = InputBox("Enter second integer number:")
        S3 = 1 * S1 + S2
    
        MsgBox S3
    End Sub
    Last edited by snb; 03-13-2017 at 08:52 PM.

  3. #3
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    9,455
    Rep Power
    10
    Hi MrIfOnly,
    Welcome to ExcelFox

    I think there are probably many good reasons ( other than the less relevant these days of “using Variant data type does consume more resources” ) to be careful with your Declaring ( Diming ) of variables. Some of which I know about.


    Anyway, to answer your specific question. I think this is the answer is fairly straight forward :
    The Input Box displays a prompt in a dialog box, waits for the user to input text or click a button, and then returns a String containing the contents of the text box. (If the user clicks Cancel, a zero-length String is returned. )

    VBA does not have to guess in this case. It is given a String


    _.....................

    Alan

    This is an example of where using a Variant can catch you out


    You probably know that you can refer to many things in VBA through their Item Number. In addition for many things you can also refer to them by their item String Number.

    For example , form here:
    https://www.excelforum.com/excel-pro...ml#post4183530

    As example a Worksheet can be referred to in ways such as these

    Worksheets.Item(1)
    Worksheets.Item(“Sheet1”)


    ( As Item is usually the default Property in VBA , then you can do this_..
    Worksheets(1)
    Worksheets(“Sheet1”)
    _.. In my opinion that is also a bit of a bad habit as you are relying on VBA to guess. I think only VBA has some of these defaults, so if you get in the habit you might do it in other languages that do not have it as the default
    )


    The danger is that you can , and people sometimes do , use a number as a String name, like

    Worksheets.Item(“128746712”)

    That is no problem when hard coding as in the last line

    But consider that you are using a variable, and are careless in how you Declare it, that is to say it is a Variant, containing the ____ 128746712
    Say a Variant type variable, var, has 128746712 in it , and you do this

    Worksheets.Item(var)

    Depending on exactly how / where / when you “filled” that variable, var, it may be a Variant holding a String , or a Variant holding a Number.
    If it is holding a String, then no problem. If it is holding a number, then you will effectively have

    Worksheets.Item(128746712)

    You can probably guess what happens here: VBA tries to reference the 128746712 th Worksheet !!!

    To be on the safe side, ( “Belt an Braces” ), I always do like this

    Worksheets.Item("" & var & "")
    or this
    Worksheets.Item("" & var)

    The above two concatenate a String or Strings ( all be it of zero length ) with a String or a number. The end result is a String

    _................


    You probably know what Rick is demonstrating: In String building you can use a & or a +
    If the variables are strings you get for S1 + S2 like
    S1 & S2, __ - the two numbers ( actually string characters ) are physically “stuck” together side by side

    If the variables are numbers you get for S1 + S2 like
    S1 + S2 __ - the numbers are added mathematically



    Alan


    P:S. Lööking at snb's response made me think again about an age old problem of trying to Put into a VBA String Variable a text which includes itself a quote or two...
    I know how to do it, but often, like now puzzle as to why.
    To get for example displayed this_..
    ____how to get “from” the current cell to the other referenced cell
    :.. the string I type in VBA code is
    __= "how to get "“from"” the current cell to the other referenced cell"
    What I am thinking is that we might be tricking VBA a bit here. - We see a correct syntaxly pair - a starting " and finishing “
    So we have two Strings
    __= "how to get "
    __= ” the current cell to the other referenced cell"
    In between we have something that again appears syntax valid to build into a String, but somehow is not. VBA is somehow confused and just talks it as “from” and puts exactly that between the other two Strings...
    Last edited by DocAElstein; 04-01-2017 at 05:24 PM.
    ….If you are my competitor, I will try all I can to beat you. But if I do, I will not belittle you. I will Salute you, because without you, I am nothing.
    If you are my enemy, we will try to kick the fucking shit out of you…..
    Winston Churchill, 1939
    Save your Forum..._
    _...KILL A MODERATOR!!

  4. #4
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    9,455
    Rep Power
    10
    Hi snb
    Quote Originally Posted by snb View Post
    -----The result of an Inputox ....
    What's the ... Inputox then








    EDIT a long time later...
    Just some Inputox Notes I wanted to dump here, as a quick place to dump them ..

    Rick said here: _..
    http://www.excelfox.com/forum/showth...tion)-InputBox
    _... about the...How To React To The Cancel Button in a VB (not Application) InputBox _.. that_..
    _...I think the below code snippet is self-explanatory (even though the StrPtr function may be new to you)...
    Code:
    Sub TesthIe()
      Dim Answer As String
      '....
      '....
      Answer = InputBox("Tell me something")
      If StrPtr(Answer) = 0 Then
        MsgBox "The user clicked Cancel, so we will exit the subroutine now."
        Exit Sub
      ElseIf Len(Answer) = 0 Then
        MsgBox "The user clicked OK without entering anything in the InputBox!"
      Else
        MsgBox "The user entered the following..." & vbLf & vbLf & Answer
      End If
      '....
      '....
    End Sub
    I don't think it is easy
    _...
    This my take on it:
    String variable:
    "Pointer" to a "Blue Print" (or Form, Questionnaire not yet filled in, a template etc.)"Pigeon Hole" in Memory, sufficient in construction to house a piece of Paper with code text giving the relevant information for the particular Variable Type. VBA is sent to it when it passes it. In a Routine it may be given a particular “Value”, or (“Values” for Objects). There instructions say then how to do that and handle(store) that(those). At Dim the created Paper is like a Blue Print that has some empty spaces not yet filled in. A String is a bit tricky. The Blue Print code line Paper in the Pigeon Hole will allow to note the string Length and an Initial start memory Location. This Location well have to change frequently as strings of different length are assigned. Instructions will tell how to do this.
    So at the address of the variable itself there is only a pointer to a memory area.
    StrPtr
    The StrPtr function “returns the address of start of that actual memory area once used in which the Unicode string is stored”. This address is not identical to the address of the variable that you use this string in Visual Basic: - at the address of the variable itself there is only a pointer to a memory area..
    The actual memory address ( for the start of the string ) may change, but it will not have been set the first time if the variable has not yet been used.
    API ddl stuff
    I expect the Functions like the StrPtr function are “WRapper functions for some API Function”. In English I think that means that that StrPtr function gives the necessary and appropriate arguments for an API Function that can return addresses of variable by running a code hidden somewhere in a File usually with a .dll extension which is usually supplied as standard with windows. The idea being that these files are a sort of directly runtime executable things that many other applications, such as Excel VBA can use in a code run. It is some sort of efficient way to allow the linking to be done to the file and the various functions loaded and used as the code such as the VBA code runs. Hence a name direct link library – The file is some special sort of runnable thing rather than just a collection of function codes. It is somehow directly Integratable into a code, as apposed to an earlier way of doing things known as static linking which had to copy a lot of stuff into a code to be used when the code ran. The word API is just a word used to intimidate. It stands for Application Program Interface. It very loosely means the things available to an Application programmer from these libraries or some similarly available coding stuff. The word Interface is often used in computing to mean the bit someone can interact with which has all the other clever stuff behind it. It is intend to give some unity / consistency / standardisation of the bit people use to do more complicated stuff that might not be directly available or might be require a lot more in depth computer knowledge to get to and use directly. If you like API is the control panel.
    These things are often a bit vague as I doubt anyone knows in the meantime what is actually going on. You may actually be using the “Excel API” when you play around with Data Base things which use stuff that takes Objects, Linking and Embedding them ( OLE ) into a VBA code. ( you use OLEDB library stuff )
    Anyway the end result of all this is that the actual address, ( as a Long number I expect ) is retuned by the API function and that passed to the wrapper function StrPtr
    Very likely the API function or the wrapper function is wired to return 0 if the things somehow does not work, or doesn’t find anything or whatever similar.
    Hence the end result of all this is I will have
    ____________StrPtr(MyVaraibleNotYetUsed)=0





    https://msdn.microsoft.com/de-de/library/bb978983.aspx
    http://www.excelfox.com/forum/showth...0192#post10192
    http://www.excelfox.com/forum/showth...-VBA#post10153
    https://www.excelforum.com/developme...ml#post4630570
    Last edited by DocAElstein; 02-16-2018 at 07:35 PM.
    ….If you are my competitor, I will try all I can to beat you. But if I do, I will not belittle you. I will Salute you, because without you, I am nothing.
    If you are my enemy, we will try to kick the fucking shit out of you…..
    Winston Churchill, 1939
    Save your Forum..._
    _...KILL A MODERATOR!!

  5. #5

  6. #6
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    9,455
    Rep Power
    10
    Quote Originally Posted by snb View Post
    Forgot your glasses ?
    The ones with my glühwein in?
    ….If you are my competitor, I will try all I can to beat you. But if I do, I will not belittle you. I will Salute you, because without you, I am nothing.
    If you are my enemy, we will try to kick the fucking shit out of you…..
    Winston Churchill, 1939
    Save your Forum..._
    _...KILL A MODERATOR!!

  7. #7
    Junior Member
    Join Date
    Mar 2017
    Posts
    7
    Rep Power
    0
    Quote Originally Posted by snb View Post
    What's the point ?
    The result of an Inputbox is always a string.
    The point was curiosity.

    A better way to state your second statement: the result of an Inputbox defaults to a string, no? After all, I can define S1 as an Integer and the result of S1 = InputBox("Enter first integer number:") would be an integer.

    Thank you, Alan, for the explanation and example of the dangers of Variant type. I'm curious about the resources issue: does VBA use a larger chunk of memory for the variant, then revert to the lesser amount of memory after the variable is assigned a value and VBA "guesses" the type? For example,

    Dim n {n is variant and uses x amount of memory}
    n= 3 {VBA says that n is type variant/integer: does the memory used go down?}

    Just for the sake of conversation, this works in C++:

    Code:
    //test stacked variables
    
    #include<iostream>
    
    using namespace std;
    
    int main()
    {
    	long S3, S1, S2;
    
    	cout << "Enter first integer number: ";
    	cin >> S1;
    	cout << "\nEnter second integer number: ";
    	cin >> S2;
    	S3 = S1 + S2;
    	cout << "\nSum is: " << S3<<endl;
    
    	return 0;
    }
    S1, S2 & S3 are all Long. So this concept in VBA is a bit of different thinking for me.

    Regards,

    CJ

  8. #8
    Senior Member
    Join Date
    Jun 2012
    Posts
    337
    Rep Power
    13
    Nur Paulaner

  9. #9
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    9,455
    Rep Power
    10
    Quote Originally Posted by snb View Post
    Nur Paulaner
    Mine is a Dunkle Bier or occaisionally a wein with my Father in Law to ease the pain of the aging Mother in Law. .. Lol..
    I expect in a few years time, I may get into Paulaner. - Some Kneipers here have an offer of what they call "A Bucket of Paulaner"
    Last edited by DocAElstein; 03-16-2017 at 07:47 PM.
    ….If you are my competitor, I will try all I can to beat you. But if I do, I will not belittle you. I will Salute you, because without you, I am nothing.
    If you are my enemy, we will try to kick the fucking shit out of you…..
    Winston Churchill, 1939
    Save your Forum..._
    _...KILL A MODERATOR!!

  10. #10
    Fuhrer, Vierte Reich DocAElstein's Avatar
    Join Date
    Aug 2014
    Posts
    9,455
    Rep Power
    10
    Hi CJ
    Quote Originally Posted by MrIfOnly View Post
    ... does VBA use a larger chunk of memory for the variant, then revert to the lesser amount of memory after the variable is assigned a value and VBA "guesses" the type? For example,
    Dim n {n is variant and uses x amount of memory}
    n= 3 {VBA says that n is type variant/integer: does the memory used go down?}
    Good question, very interesting question, .. but I am afraid I do not know the answer.
    Sounds like you know generally more about than computing then me. I have just been learning VBA and Excel for a couple of years now. That is about the limit of my knowledge.
    I do not understand the code snippet you Gave

    _..___


    I have picked up a couple of things after many many hard hours of asking and googling, for example: ...,_..

    _.. A Long variable always uses the same amount of space, regardless of the number. Makes sense I suppose, like pseudo 000.1234 and 145.4567 need the same amount of memory
    _.. A String is very efficient apparently as the variable gives just the address of where info is about the string, like where it starts from in memory, and its length.
    I did some experiments and found that as I changed a String’s size, the memory location of where the string actually was held changed to accommodate the different length. So it is using just the memory it needs and adjusting each time.
    https://www.mrexcel.com/forum/excel-...ml#post4411660
    https://www.mrexcel.com/forum/excel-...lstring-4.html
    https://www.mrexcel.com/forum/excel-...ml#post4413433
    https://www.mrexcel.com/forum/excel-...ml#post4415958
    https://www.mrexcel.com/forum/excel-...n-code-me.html


    This is the info I often include in codes I give ( or rather inflict on OPs I help ).
    I confess, I do not fully understanding what I am talking about, Lol... – go easy on me - I am not a computer professional, Lol..
    Most Porofessionals i ask do not seem to know much better.. lol..

    Code:
    Sub DimAlan()
    Dim Ws As Worksheet                        ' EP Dim: For the Variable type declared, there should be some Blue Print or master Instruction list. If not The code will error at the start as it need to examine and therefore prepare for usage of the variable in the code run. The variable itself will go to some “Pigeon hole” that has a copy of the instructions or in some way has information on how to use the original instructions such that it can distinguish between different variables of the same type. When the code meets the variable it will look in the Pigeon Hole Pointer for instructions as to what to do in various situations. Knowing of the type allows in addition to get easily at the Methods and Properties through the applying of a period ( .Dot) ( intellisense ). Note this is a look up type list and may not be a guarantee that every offered thing is available – most will be typically.
     Set Ws = ThisWorkbook.Worksheets.Item(1)  ' EP Set: Setting to a Class will involve the use of an extra New at this code line. I will then have an Object referred to as an instance of a Class. At this point I include information on my Pointer Pigeon hole for a distinct distinguishable usage of an Object of the Class. For the case of something such as a Workbook this instancing has already been done, and in addition some values are filled in specific memory locations which are also held as part of the information in the Pigeon Hole Pointer. Wed will have a different Pointer for each instance. In most excel versions we already have a few instances of Worksheets. Such instances Objects can be further used., - For this a Dim to the class will be necessary, but the New must be omitted at Set. I can assign as many variables that I wish to the same existing instance
    
    
    
    
    '_-Dim: Prepares "Pointer" to a "Blue Print" (or Form, Questionaire not yet filled in, a template etc.)"Pigeon Hole" in Memory, sufficient in construction to house a piece of Paper with code text giving the relevant information for the particular Variable Type. VBA is sent to it when it passes it. In a Routine it may be given a particular “Value”, or (“Values” for Objects).  There instructions say then how to do that and handle(store) that(those). At Dim the created Paper is like a Blue Print that has some empty spaces not yet filled in. A String is a a bit tricky. The Blue Print code line Paper in the Pigeon Hole will allow to note the string Length and an Initial start memory Location. This Location well have to change frequently as strings of different length are assigned. Instructiions will tell how to do this. Theoretically a specilal value vbNullString is set to aid in quich checks.. But..http://www.mrexcel.com/forum/excel-questions/361246-vbnullstring-2.html#post44116
    '_-So A variable in VBA is like the Link to the part of a URL string reducing size site where a few things about the actual Final site is informed about. This area in that site, like a pigion Hole to which the variable refers, ( the "pigeon hole" location address, and all its contents would be defined as the "Pointer". Amongst other things it has a link, a "Pointing part", pointing to actually where all the stuff is
    
    'EP Dim: For Object variables: Address location to a "pointer". That has all the actual memory locations (addresses) of the various property values , and it holds all the instructions what / how to change them , should that be wanted later. That helps to  explain what occurs when passing an Object to a Call ed Function or Sub Routine By Val ue. In such an occurrence, VBA actually  passes a copy of the pointer.  So that has the effect of when you change things like properties on the local variable , then the changes are reflected in changes in the original object. (The copy pointer instructs how to change those values, at the actual address held in that pointer). That would normally be the sort of thing you would expect from passing by Ref erence.  But as that copy pointer "dies" after the called routine ends, then any changes to the Addresses of the Object Properties in the local variable will not be reflected in the original pointer. So you cannot actually change the pointer.)
     'EP Set: Fill or partially Fill: Setting to a Class will involve the use of an extra New at this code line. I will then have an Object referred to as an instance of a Class. At this point I include information on my Pointer Pigeon hole for a distinct distinguishable usage of an Object of the Class. For the case of something such as a Workbook this instancing has already been done, and in addition some values are filled in specific memory locations which are also held as part of the information in the Pigeon Hole Pointer. We will have a different Pointer for each instance. In most excel versions we already have a few instances of Worksheets. Such instances Objects can be further used., - For this a Dim to the class will be necessary, but the New must be omitted at Set. I can assign as many variables that I wish to the same existing        http://www.excelforum.com/excel-programming-vba-macros/1138804-help-understanding-class-instancing-cant-set-ws-new-worksheet-intellisense-offers-it-4.html#post4387191instance
    
    
    
    Dim str As String '         ' Prepares "Pointer" to a "Blue Print" (or Form, Questionaire not yet filled in, a template etc.)"Pigeon Hole" in Memory, sufficient in construction to house a piece of Paper with code text giving the relevant information for the particular Variable Type. VBA is sent to it when it passes it. In a Routine it may be given a particular “Value”, or (“Values” for Objects).  There instructions say then how to do that and handle(store) that(those). At Dim the created Paper is like a Blue Print that has some empty spaces not yet filled in. A String is a a bit tricky. The Blue Print code line Paper in the Pigeon Hole will allow to note the string Length and an Initial start memory Location. This Location well have to change frequently as strings of different length are assigned. Instructiions will tell how to do this. Theoretically a specilal value vbNullString is set to aid in quich checks.. But..http://www.mrexcel.com/forum/excel-questions/361246-vbnullstring-2.html#post44116
    Dim Lenf As Long '          ' Long is very simple to handle, - final memory "size" type is known (123.456 and 000.001 have same "size" computer memory ) , and so a Address suggestion can be given for the next line when the variable is filled in.  '( Long is a Big whole Number limit (-2,147,483,648 to 2,147,483,647) If you need some sort of validation the value should only be within the range of a Byte/Integer otherwise there's no point using anything but Long.--upon/after 32-bit, Integers (Short) need converted internally anyways, so a Long is actually faster. )
    End Sub
    So I have a very rough idea of some variables.
    But your question is interesting, as I do not have a good 'ExPlanation for a Variant yet.
    If I ever get one, and can answer your question I will reply again

    _...
    I think the extra memory needed ( if indeed that is the case ) is less relevant as memory becomes cheaper and easier and computers quicker...
    But there are both dangers ,
    _ as I indicated,
    and
    _ also very useful uses of a Variant, - Often it makes an initialisation of a variable easy to check for by choosing Variant initially, then checking later if it is
    _.. Empty ( not yet used )
    _.. Null ( used ( attempted ) but not filled with correct data ) https://eileenslounge.com/viewtopic....244579#p244579
    _.. IsArray( ) etc . ... https://www.excelforum.com/excel-new...ml#post4157615



    Alan



    P.s. I think it is still correct what me and snb said, - The input box always returns ( gives, presents , or chucks out ) a String.

    But, I think, however, VBA is very tolerant at like putting a String which “looks” like a number into a number variable ( or accepting it in such a variable ) and taking it then as a number,.
    That can be achieved either
    _ as you demonstrated ,
    or
    _ when putting a String which “looks” like a number into a function’s argument which takes as argument a number. I think one says that VBA will “co coerce” the variable into the correct type.

    I do not know for sure, but I think in other languages it is not always as tolerant and you have to be careful to include bits to convert the type appropriately like CStr( ) CDbl( ) etc...
    You probably know that better than me. I know just VBA and very very old languages from about 25 years ago.

    In fact I favour handling all my numbers in String variables, as I have found that I have less format changing problems caused by Date format differences and . and , different conventions for the decimal separator and thousand separator.
    http://www.eileenslounge.com/viewtopic.php?f=27&t=22850
    Last edited by DocAElstein; 01-13-2019 at 02:43 PM.
    ….If you are my competitor, I will try all I can to beat you. But if I do, I will not belittle you. I will Salute you, because without you, I am nothing.
    If you are my enemy, we will try to kick the fucking shit out of you…..
    Winston Churchill, 1939
    Save your Forum..._
    _...KILL A MODERATOR!!

Similar Threads

  1. Replies: 2
    Last Post: 02-27-2019, 05:35 PM
  2. VBA To Compare Multiple Cells
    By x010 in forum Excel Help
    Replies: 4
    Last Post: 08-31-2013, 01:53 AM
  3. Populate Ribbon Controls On Load Dynamically Through VBA Variables
    By phxpoolplayer in forum Excel Ribbon and Add-Ins
    Replies: 1
    Last Post: 04-20-2013, 01:51 AM
  4. Replies: 2
    Last Post: 12-19-2012, 08:28 AM
  5. Split Range into Multiple Columns VBA
    By Admin in forum Excel and VBA Tips and Tricks
    Replies: 3
    Last Post: 03-07-2012, 10:53 PM

Posting Permissions

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