+ Reply to Thread
Results 1 to 55 of 55

VBA Developers Handbook, 2nd Edition. questions on procedures and functions

Hybrid View

  1. #1
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    so im reading VBA Developer's Handbook, 2nd edition and i have a question about a function (why it's returning 0, when it should be greater than 0). see below:

    Public Function dhCountInCaseS(strText As String, strFind As String, Optional lngCompare As VbCompareMethod = vbBinaryCompare) As Long
        Dim lngCount As Long
        Dim lngPos As Long
        'this search is case sensitive so "A" is not the same as "a"
        'if there's nothing to find, there surely can't be an found so return 0
        If Len(strFind) > 0 Then
            lngPos = 1
            Do
                lngPos = InStr(lngPos, strText, strFind, lngCompare)
                If lngPos > 0 Then
                    lngCount = lngCount + 1
                    lngPos = lngPos + Len(strFind)
                End If
            Loop While lngPos > 0
        Else
            lngCount = 0
        End If
        dhCountIn = lngCount
    End Function
    and here is the procedure

    Sub Count_Vowels()
        Dim strText As String
        Dim intVowels As Long
        
        strText = "THIS IS A TEST OF THE NATIONAL BROADCASTING SYSTEM"
        
        intVowels = dhCountInCaseS(strText, "A") + dhCountInCaseS(strText, "E") + dhCountInCaseS(strText, "I") + _
        dhCountInCaseS(strText, "O") + dhCountInCaseS(strText, "U")
        
        Debug.Print intVowels
    End Sub
    Is there a problem with the function or how i'm implementing the procedure?
    Last edited by dmcgov; 03-25-2019 at 07:29 AM.

  2. #2
    Forum Expert XLent's Avatar
    Join Date
    10-13-2010
    Location
    Northumberland, UK
    MS-Off Ver
    various
    Posts
    2,706

    Re: Function returns 0 when it the test is run but it should be greater than 0

    there's nothing wrong, per se, aside the penultimate line in your Function... i.e. dhCountInCaseS

  3. #3
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: Function returns 0 when it the test is run but it should be greater than 0

    so onto another issue with the following function:

    Public Function dhExtractString(ByVal strIn As String, ByVal intPiece As Integer, _
        Optional ByVal strDelimiter As String = dhcDelimiters) As String
        
        Dim lngPos As Long
        Dim lngpos1 As Long
        Dim lngLastPos As Long
        Dim intLoop As Integer
        
        lngPos = 0
        lngLastPos = 0
        intLoop = intPiece
        
        'if there's more that on delimiter, map them all to the first one
        If Len(strDelimiter) > 1 Then
            strIn = dhTranslate(strIn, strDelimiter, Left$(strDelimitier, 1))
        End If
        strIn = dhTrimAll(strIn)
        Do While intLoop > 0
            lngLastPos = lngPos
            lngpos1 = InStr(lngPos + 1, strIn, Left$(strDelimiter, 1))
            If lngpos1 > 0 Then
                lngPos = lngpos1
                intLoop = intLoop - 1
            Else
                lngPos = Len(strIn) + 1
                Exit Do
            End If
        Loop
        
        End Function
    no matter what i try, it always says "Constant expression required" even though it's optional. here is what i tried to use:

    Public Sub TestExtract(strIniText As String)
    Const dhcdelimiters As String = "=,"
    
    Dim intI As Integer
    Dim strText As String
    dhcdelimiters = "=,"
    intI = 2
    Do While True
        strText = dhExtractString(strIniText, intI, "=,")
        If Len(strText) = 0 Then
            Exit Do
        End If
        Debug.Print strText
        intI = intI + 1
    Loop
    End Sub
    Sub test_E_nw()
    Const dhcdelimiters As String = "=,"
    
    dhcdelimiters = "=,"
    Debug.Print TestExtract("ItemsToBuy=Milk,Bread,Peas")
    End Sub
    even if i add dhcDelimiters to the function, it still fails at the function. what am i implementing wrong?

  4. #4
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: Function returns 0 when it the test is run but it should be greater than 0

    thanks @xlent. my goof. appreciate you taking the time to debug this for me. now all working.

  5. #5
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: Function returns 0 when it the test is run but it should be greater than 0

    You need to remove this:

    dhcdelimiters = "=,"
    Everyone who confuses correlation and causation ends up dead.

  6. #6
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: Function returns 0 when it the test is run but it should be greater than 0

    ya i had tried that solution but did remove it from the procedures. however when i debug the project, i still get the same error on the function, this line:

    Public Function dhExtractString(ByVal strIn As String, ByVal intPiece As Integer, _
        Optional ByVal strDelimiter As String = dhcDelimiters) As String
    and it highlights dhcDelimiters.
    Attached Images Attached Images

  7. #7
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    The constant scope needs to be visible to the function - so either Public or if all the code is in the same module, at module level in that module.

  8. #8
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    yes i understand, but even if i comment out the code after the function, when i try to compile, it always says the same error in post #6, so the problem is that the function error's out. i have even copied the code directly from the book, but still get the same error. so what is wrong with the code in the function. that is where the error is. so one note, is that i put the const dhcDelimiters in the actual function, so compile works but when i run one of the procedures, it still goes back to the constant error. what is my limited brain not understanding?

  9. #9
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Code module should start with:

    Public Const dhcdelimiters As String = "=,"
    Then:
    Public Sub TestExtract(strIniText As String)
    
    Dim intI As Integer
    Dim strText As String
    intI = 2
    Do While True
        strText = dhExtractString(strIniText, intI, "=,")
        If Len(strText) = 0 Then
            Exit Do
        End If
        Debug.Print strText
        intI = intI + 1
    Loop
    End Sub
    Sub test_E_nw()
        TestExtract "ItemsToBuy=Milk,Bread,Peas"
    End Sub
    and the function should be:

    Public Function dhExtractString(ByVal strIn As String, ByVal intPiece As Integer, _
        Optional ByVal strDelimiter As String = dhcDelimiters) As String
        
        Dim lngPos As Long
        Dim lngpos1 As Long
        Dim lngLastPos As Long
        Dim intLoop As Integer
        
        lngPos = 0
        lngLastPos = 0
        intLoop = intPiece
        
        'if there's more that on delimiter, map them all to the first one
        If Len(strDelimiter) > 1 Then
            strIn = dhTranslate(strIn, strDelimiter, Left$(strDelimitier, 1))
        End If
        strIn = dhTrimAll(strIn)
        Do While intLoop > 0
            lngLastPos = lngPos
            lngpos1 = InStr(lngPos + 1, strIn, Left$(strDelimiter, 1))
            If lngpos1 > 0 Then
                lngPos = lngpos1
                intLoop = intLoop - 1
            Else
                lngPos = Len(strIn) + 1
                Exit Do
            End If
        Loop
        
        End Function

  10. #10
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    sigh, im without words. i copied everything verbatim from your post. cant get rid of the constant error.

    here is two of my public procedure, neither work.

    Public Sub test_E_nw()
        Public Const dhcDelimiters As String = "=,"
        TestExtract "ItemsToBuy=Milk,Bread,Peas"
    End Sub
    Public Sub test_E_nw2()
        Public Const dhcDelimiters As String = "=,"
        Debug.Print TestExtract("ItemsToBuy=Milk,Bread,Peas")
    End Sub
    everything is in the same module (only have one). should i just move on?

    is maybe something wrong with my excel program? or is it just me (Probably). let me attach my workbook, and maybe you can take a peek at it, see if that's whats wrong?
    Attached Files Attached Files

  11. #11
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Quote Originally Posted by dmcgov View Post
    sigh, im without words. i copied everything verbatim from your post.
    You really didn't.

    The Public Const line should appear once, at the top of the module, and nowhere else.

  12. #12
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    thanks again for sticking the out on me, i knew is was my mistake.

  13. #13
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    No worries - we all do it!

  14. #14
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    and that helped me solve a couple of other issues that weren't working as procedures. now i can cross off chapter 1. hopefully this makes me a better coder.

  15. #15
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    so on to the next chapter. i have this function, how to correctly write a procedure to test it. here's the function:

    Public Function dhArrayAverage(varArray As Variant) As Variant
        Dim varItem As Variant
        Dim varSum As Variant
        Dim lngCount As Long
        
        If IsArray(varArray) Then
            For Each varItem In varArray
                varSum = varItem + varSum
                lngCount = lngCount + 1
            Next
            dhArrayAverage = varSum / lngCount
        Else
            dhArrayAverage = Null
        End If
    End Function
    and there are the procedures that i have tried:

    Sub test_AAAMASDAMAMAM()
        Debug.Print "the array average of 1,2,3 is " & dhArrayAverage(1, 2, 3)
    End Sub
    this generates an error
    then i tried this
    Sub test_AAAMASDAMAMAM()
        Debug.Print "the array average of 1,2,3 is " & dhArrayAverage("1", "2", "3")
    End Sub
    that generates an error as well. finally i tried this:

    Sub test_AAAMASDAMAMAM()
        Debug.Print "the array average of 1,2,3 is " & dhArrayAverage("1,2,3")
    End Sub
    that does not generate an error but does not output the average, it's just blank.

    what am i doing wrong?
    Last edited by dmcgov; 03-26-2019 at 08:22 AM. Reason: straightened out the [CODE] blocks

  16. #16
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    It's expecting an array, not three arguments, or a string, so:

    dhArrayAverage(Array(1, 2, 3))

  17. #17
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    so another question on the numbers chapter. this has to do with factorials and recursive factorials. if i run the following procedure, shouldn't they both be the same (or am i not understanding what recursive means?

    Sub test_FR_and_F_nw()
        Debug.Print "the factorial of 19 is " & dhFactorial(19)
        Debug.Print "the factorial recursive of 19 is " & dhFactorialRecursive(19)
    end sub


    the result of running this is:

    the factorial of 19 is 1.21645100408832E+17
    the factorial recursive of 19 is 19

    i did find a typo which i fixed so here is the recursive function:

    Public Function dhFactorialRecursive(intX As Integer) As Double
        If intX < 0 Or intX > 170 Then
            dhFactorialRecursive = 0
        ElseIf intX = 0 Then
            dhFactorialRecursive = 1
        Else
            dhFactorialRecursive = intX * dhFactorialRecursive(intX - 1)
        End If
    End Function
    what am i doing wrong?

  18. #18
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    thanks, that will help me in several of the Array functions. appreciate the help. got two more that aren't working from chapter 2. will post them separately. then im done with the chapter and on to three.

  19. #19
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Only 13 to go.

  20. #20
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    im learning at a fast pace, thanks for all your help. now onto the next function that is erroring out, i see why, but don't know how.

    Sub test_AAAMASDAMAMAM()
        Debug.Print "the array mode of 1,2,3,4,5,6,7,8 is " & dhArrayMode(Array(1, 2, 3, 4, 5, 6, 7, 8))
    End Sub
    and here is the function:

    Public Function dhArrayMode(varArray As Variant) As Variant
        Dim varItem As Variant
        Dim varLast As Variant
        Dim lngCount As Long
        Dim lngOccur As Long
        Dim lngLastOccur As Long
        Dim lngTotalOccur As Long
        
        If IsArray(varArray) Then
            ' Sort the array so elements are in order
            Call dhQuickSort(varArray)
            ' Capture the first item
            varItem = varArray(LBound(varArray))
            ' Loop through all the elements
            For lngCount = LBound(varArray) To UBound(varArray)
                ' Increment the occurrence counter
                lngOccur = lngOccur + 1
                ' If the value is not the same as the last one,
                ' see if the occurrences of the last value
                ' exceed the current maximum
                If varArray(lngCount) <> varLast Then
                    If lngLastOccur >= lngTotalOccur Then
                        ' If so, make it the new maximum and
                        ' capture the prior value
                        lngTotalOccur = lngLastOccur
                        varItem = varArray(lngCount - 1)
                    End If
                    ' Record this element as the last one visited
                    varLast = varArray(lngCount)
                    ' Reset the counter lngOccur = 0
                End If
                lngLastOccur = lngOccur
            Next
            ' Return the value with the most occurrences
            ' (make sure to check the final value)
            If lngOccur > lngTotalOccur Then
                dhArrayMode = varArray(lngCount - 1)
            Else
                dhArrayMode = varItem
            End If
        Else
            dhArrayMode = Null
        End If
    is't erroring out on this line

    varItem = varArray(lngCount - 1)
    when i check the locals window,i see that lngTotalOccur and lngLastOccur are 0, the varItem is 1 and lngCount is 0 (thats where the error is, can't have a negative number for varArray).

    did i make a typo or something (i have checked the code a couple of times but don't see the error). what is wrong with the code (my mistake most likely).
    Last edited by dmcgov; 03-26-2019 at 09:09 AM. Reason: added parenthesis

  21. #21
    Forum Guru bakerman2's Avatar
    Join Date
    10-03-2012
    Location
    Antwerp, Belgium
    MS-Off Ver
    MSO Home and Business 2024
    Posts
    7,499

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    OP moves with fast pace through Functions.
    Last edited by bakerman2; 03-26-2019 at 09:30 AM.
    Avoid using Select, Selection and Activate in your code. Use With ... End With instead.
    You can show your appreciation for those that have helped you by clicking the * at the bottom left of any of their posts.

  22. #22
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Quote Originally Posted by bakerman2 View Post
    OP moves with fast pace through Functions.
    well yup, basically i run through each chapter and the ones that don't work i add a "_nw" to. that way i can quickly find the ones that are "not working". by reading each chapter through the end, i can fix a lot of mistakes. but yes, i am cranking out the questions. really glad you guys are lending a hand. this will go a long way into making me a better coder.

  23. #23
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    No, I think there are actually two errors in that code (One at least is just typographical). It should be:

    Public Function dhArrayMode(varArray As Variant) As Variant
        Dim varItem As Variant
        Dim varLast As Variant
        Dim lngCount As Long
        Dim lngOccur As Long
        Dim lngLastOccur As Long
        Dim lngTotalOccur As Long
        
        If IsArray(varArray) Then
            ' Sort the array so elements are in order
            Call dhQuickSort(varArray)
            ' Capture the first item
            varLast = varArray(LBound(varArray))
            ' Loop through all the elements
            For lngCount = LBound(varArray) To UBound(varArray)
                ' Increment the occurrence counter
                lngOccur = lngOccur + 1
                ' If the value is not the same as the last one,
                ' see if the occurrences of the last value
                ' exceed the current maximum
                If varArray(lngCount) <> varLast Then
                    If lngLastOccur >= lngTotalOccur Then
                        ' If so, make it the new maximum and
                        ' capture the prior value
                        lngTotalOccur = lngLastOccur
                        varItem = varArray(lngCount - 1)
                    End If
                    ' Record this element as the last one visited
                    varLast = varArray(lngCount)
                    ' Reset the counter
                    lngOccur = 0
                End If
                lngLastOccur = lngOccur
            Next
            ' Return the value with the most occurrences
            ' (make sure to check the final value)
            If lngOccur > lngTotalOccur Then
                dhArrayMode = varArray(lngCount - 1)
            Else
                dhArrayMode = varItem
            End If
        Else
            dhArrayMode = Null
        End If
    End Function

  24. #24
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    thanks, i use notepad++ for some of my coding, just ran a compare. i see the two issues. thanks for pointing that out. one of those "cant see the forest for the tree's issue".

  25. #25
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    At least it wasn't your error.

  26. #26
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    I get the same result with both.

  27. #27
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Quote Originally Posted by rorya View Post
    I get the same result with both.
    sometimes i get hiccups with excel not working as expected, so let me load up my workbook to see if you are getting the same result as I am. if you run this and it works, it just means my version of excel (office 365) is to blame.
    Attached Files Attached Files

  28. #28
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Yes, I get the same 1.21E17 value for both.

  29. #29
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    what version of excel are you using Rorya?

    btw, closing chapter 2, on to dates and times

  30. #30
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    2010 (32 bit)

  31. #31
    Forum Guru bakerman2's Avatar
    Join Date
    10-03-2012
    Location
    Antwerp, Belgium
    MS-Off Ver
    MSO Home and Business 2024
    Posts
    7,499

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Using XL2007 they are both the same. Also using Application.Fact(19) gives the same result.

  32. #32
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    quick question, does anyone have the CD from this book? looking to get the Holidays.xml or Holidays.mdb file.

  33. #33
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    so only two procedures are not working from chap 3. here is the first function:

    Public Function dhFirstDayInQuarter(Optional dtmDate As Date = 0) As Date
        ' Returns the last day in the quarter specified by the
        ' date in dtmDate.
        Const dhcMonthsInQuarter As Integer = 3
        Dim intMonth As Integer
    
        'did the caller pass in a date? if not, use the current date
        If dtmDate = 0 Then
            dtmDate = Date
        End If
        
        'calculate the first month in the quarter
        intMonth = Int((Month(dtmDate) - 1) / dhcMonthsInQuarter) * dhcMonthsInQuarter + 1
        
        dhFirstQuaterInYear = DateSerial(Year(dtmDate), intMonth, 1)
    End Function
    and here is the procedure that doesn't work (prints 12:00:00 AM)

    Sub test_FDIQ_nw()
        Debug.Print dhFirstDayInQuarter()
    End Sub
    is the book wrong or did i make a typo?

  34. #34
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    thoughts anyone?

  35. #35
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Here's the function signature:

    Public Function dhFirstDayInQuarter(Optional dtmDate As Date = 0) As Date
    And here's the assignment of the result:

    dhFirstQuaterInYear = DateSerial(Year(dtmDate), intMonth, 1)
    See the problem?

    Option Explicit is your friend.
    Entia non sunt multiplicanda sine necessitate

  36. #36
    Forum Guru bakerman2's Avatar
    Join Date
    10-03-2012
    Location
    Antwerp, Belgium
    MS-Off Ver
    MSO Home and Business 2024
    Posts
    7,499

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    This line
    dhFirstQuaterInYear = DateSerial(Year(dtmDate), intMonth, 1)
    needs to be
    dhFirstDayInQuarter = DateSerial(Year(dtmDate), intMonth, 1)

  37. #37
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    thanks, thought it was me (mistyping). so the other function that doesn't work is a doozy for me.

    the function thats tripping me up is below:

    Private Function GetTimeDelimiter() As String
        Dim lngLCID As Long
        Dim lngLen As Long
        Dim strBuffer As String
        Const MAX_CHARS = 4
        
        lngLCID = GetSystemDefaultLCID()
        strBuffer = Space(MAX_CHARS + 1)
        lngLen = GetLocalInfo(lngLCID, LOCAL_STIME, strBuffer, Len(strBuffer))
        GetTimeDelimiter = Left$(strBuffer, lngLen - 1)
    End Function

    the procedure that i am running is:

    Sub test_FI_nw()
        'this needs GetSystemDefaultLCID & GetLocalInfo which seem to be unsupported on microsoft's site
        Dim dtmStart As Date
        Dim dtmEnd As Date
        On Error GoTo ErrHandler:
        
        
        dtmStart = #1/1/2019 12:00:00 PM#
        dmtEnd = #3/27/2019 8:10:45 AM#
        
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "D H")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "D H M")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "D H M S")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "D H:MM")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "D HH:MM")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "D HH:MM:SS")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "H M")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "H:MM")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "H:MM:SS")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "M S")
        Debug.Print dhFormatInterval(dtmStart, dtmEnd, "M:SS")
        
    ErrHandler:
    
    End Sub
    it complains that "GetSystemDefaultLCID" and "GetLocalInfo" are not defined. from reading the text i understand that these are api calls. i googled the internet for both functions but came up empty (microsoft says they are depreciated i think). is there a way to declare the api function calls in the declaration section?

  38. #38
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    The two API calls are at the top of the DateTime.bas file:

    Private Declare Function GetLocaleInfo _
     Lib "kernel32" Alias "GetLocaleInfoA" _
     (ByVal Locale As Long, ByVal LCType As Long, _
     ByVal lpLCData As String, ByVal cchData As Long) As Long
    
    Private Declare Function GetSystemDefaultLCID _
     Lib "kernel32" () As Long
    I have attached the two files you mentioned.
    Attached Files Attached Files

  39. #39
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    thanks rorya for the zip, helped me to close chapter 3. just so you know i have the ebook, so don't have access to the CD. trying to find out if sybex still has that with the printed book. be so much easier if i could just copy.

    so finished with chapter 4 and 5, moving on to 6 "arrgh" = heavy topic. reading on classes from other excel sites. not for the faint of heart.

  40. #40
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    so i am having an issue with my new class module, getting a run time error 424, object required.

    here is my module code:

    Sub test_uf2()
    Dim cls_btnCode As clsCode
    Set cls_btnCode = New clsCode
    End Sub
    i get the error on the set cls_btnCode statement.

    here is my class module:

    Dim cls_btnCode As String * 8192
    Private Sub Class_Initialize()
    btn_Gen_uf2.TextBox1.Value = ""
    btn_Gen_uf2.Show
    cls_btnCode = btn_Gen_uf2.TextBox1.Value
    If cls_btnCode <> "" Then MsgBox cls_btnCode
    errhandler:
     MsgBox "you have exceeded 8192 characters " & Len(TextBox1.Value)
    End Sub
    what am i doing wrong?

    it behaves correctly in that it shows the userform, lets me type, tracks the character count. when i press ok, it displays a msgbox which contains the correct text.

  41. #41
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    You need an Exit Sub before errhandler:

  42. #42
    Forum Expert romperstomper's Avatar
    Join Date
    08-13-2008
    Location
    England
    MS-Off Ver
    365, varying versions/builds
    Posts
    22,056

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    An On Error statement wouldn’t hurt either.

    I suspect the underlying issue is not specifying the form that contains the button.

  43. #43
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Also, you don't want to be breaking encapsulation like that, you should be passing the UserForm object into the class. Oh, and don't use the default instances of user forms, ie. Never use NameOfUserForm.Show

    You should be using them properly:
    Dim uf As btn_Gen_uf2
    Set uf = new btn_Gen_uf2
    
    uf.Show
    The default instances won't always be what you expect them to be

  44. #44
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    thanks @shg and @rorya for that info. @kyle123, here is code that is working but how do i get the data from the code window into the userform that the button generator makes?

    here's the module code:

    Public uf As btn_Gen_uf2
    Sub test_uf2()
        count = 2
        For counter = 1 To count
            Dim cls_btnCode As clsCode
            Set cls_btnCode = New clsCode
        Next counter
    End Sub
    and here is the class module code:

    Dim cls_btnCode As String * 8192
    Private Sub Class_Initialize()
    Set uf = New btn_Gen_uf2
    uf.TextBox1.Value = ""
    uf.Label2.Caption = "Count: " & Len(uf.TextBox1.Value)
    uf.Show
    cls_btnCode = uf.TextBox1.Value
    End Sub
    and here is my userform code:

    Private Sub TextBox1_Change()
        TextBox1.SetFocus
        Label3.Caption = "CommandButton" & counter
        Dim x As Long
        x = Len(TextBox1.Value)
        If x <= 8192 Then
        Label2.Caption = "Count: " & Len(TextBox1.Value)
        End If
        Exit Sub
    End Sub
    so i tried to put a msgbox in the module code to get the data from the code window but it failed on that line. how do i do that?

  45. #45
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    so nevermind, i got it working.

    i added this (finally worked) to the module and now i can get the info out to the module.

    MsgBox uf.TextBox1.Value
    now the question is how to get that code into the userform that the button generates. but i have to wait to get home to get the file that does that. didn't update my dropbox.

  46. #46
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    I've got no idea what that code is supposed to be doing, it doens't seem to make a lot of sense unless you are trying to create multiple userforms (even then it wouldn't work). I don't understand why you are using a class for this, there doesn't seem to be any need?

    What do you want the code to do?

  47. #47
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    so the button generator generates multiple buttons. other than the spacing, i have that working. so now that the class module clsCode is working. i now need that code to 'attach' it to the buttons (buttons need to do something right?) but the file that i need to do this is at home. so the question will have to wait till i can get to my laptop. im sure once i pull this all together, it will make sense (at least i hope that it will). please be patient as this grasshopper is still learning the ropes

  48. #48
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    Are you still trying to do that IDE automation where you are writing code with code?

  49. #49
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    yes, isn't that the way im supposed to do it? i thought that my first approach was wrong (in that i did it all at design time).

  50. #50
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    I don't think you should do any of it at design time. I don't understand why you'd want to.

  51. #51
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    am i still doing it wrong?

  52. #52
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    It really depends why you want to do it. Why do you want to do any of it at design time? - What's the purpose of the project?

  53. #53
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    well at first, all i knew was to create it at design time (showing my lack of knowledge). then you and others said it's not the way to do it. hence writing code that makes code and the use of class modules. i thought that was the right way to do it. and since i didn't have the knowledge, i got the VBA book to learn more. now im on chapter 6 which goes into more detail about class modules. which is why i wrote the clsCode code to get the actual code for the button. do i still not understand the correct way to do this? and the purpose was to do this right (and not at design time, which i said was all that i knew at the time)

  54. #54
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,239

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    If you want to have a userform that you can add a dynamic number of buttons to that have similar behaviour, then do it all at runtime:

    Module:
    Sub test()
        
        Dim uf As DynamicForm
        Set uf = New DynamicForm
        
        uf.NumberOfButtons = 5
        uf.Show
        
    End Sub
    Userform:
    Private buttonHandlers() As ButtonHandler
    
    Public Property Let NumberOfButtons(ByVal quantity As Long)
        
        Dim hndlr   As ButtonHandler
        Dim x       As Long
        
        ReDim buttonHandlers(quantity)
        
        For x = LBound(buttonHandlers) To UBound(buttonHandlers)
            Set buttonHandlers(x) = New ButtonHandler
            Set buttonHandlers(x).Button = Me.Controls.Add("Forms.CommandButton.1")
            With buttonHandlers(x).Button
                .Left = 10
                .Height = 30
                .Top = (x * .Height) + 10
                .Caption = "Button" & x + 1
                .Width = 80
            End With
        Next x
        
        Me.Width = 110
        Me.Height = 30 * (UBound(buttonHandlers) + 1) + 50
        
    End Property
    
    
    Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
        Cancel = 1: Me.Hide
    End Sub
    Class:
    Public WithEvents Button As MSForms.CommandButton
    
    Private Sub Button_Click()
        MsgBox "Your code goes here"
    End Sub

  55. #55
    Valued Forum Contributor dmcgov's Avatar
    Join Date
    11-11-2015
    Location
    Florida, USA
    MS-Off Ver
    Office 365 Business
    Posts
    1,518

    Re: VBA Developers Handbook, 2nd Edition. questions on procedures and functions

    ahh, that is it very helpful. can't wait to get home to do this. thanks for hanging in there.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Which test is best for abnormal returns?
    By WASIM_PAK in forum Excel General
    Replies: 0
    Last Post: 08-27-2015, 11:39 AM
  2. Replies: 1
    Last Post: 08-10-2015, 10:30 AM
  3. Replies: 4
    Last Post: 08-07-2013, 11:29 AM
  4. return a value for a greater than less than logic test
    By azruss in forum Excel Formulas & Functions
    Replies: 2
    Last Post: 08-03-2013, 12:50 PM
  5. Replies: 5
    Last Post: 12-09-2012, 11:04 PM
  6. WorksheetFunction.Sum returns 0 for array of elements whose sum is greater than 0
    By RowanB in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 01-12-2012, 06:15 AM
  7. Change Test Color If Value is Greater Than Another
    By BluTalon in forum Excel General
    Replies: 8
    Last Post: 11-07-2008, 10:24 AM

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1