简体   繁体   中英

How do I debug a trivial vba function in Excel 2016?

I am trying to debug a simple vba function that returns the array it is given but stops once it reaches an empty cell:

Function Test2(source() As Variant) As Collection
    Debug.Print "Hello"
    Dim i As Integer
    i = 1
    Do While Not IsEmpty(source(i))
        Test2.Add source(i).Value
        Debug.Print source(i).Value
        i = i + 1
    Loop

End Function

When I pass an array to this function by writing, for example, =Test2(A:A) in a cell I get a #VALUE! error and see nothing printed to the Immediate Window.

I am less interested in finding out what is wrong with this function than how to use the tools to find the issue. Why is "TEST" not being printed to the Immediate Window, and, if there is a syntax error in my program, why does the compiler not set a breakpoint?

Looking at your function again, look down near the End Function statement. In order to return a value from a function, you need to set the function name to the value to be returned. So, if you want to return the value "1" (without the quotes) your last line before End Function should say ....

Test2 = 1

That is one possible reason for your #value error. There could be other reasons as well. but look at that first.

Remove those brackets in source() variant. Simply Source. You can use Range as data type instead of Variant, as your input is Range(A:A Declare a new collection for adding values to the collection. For iteration i used For each method. Hope you can get an idea about your error from this below code

  Function Test2(source As Variant) As Collection
    Dim c As New Collection
    Dim cell As Range
    Debug.Print "Hello"
    Dim i As Integer

    i = 0
     For Each cell In source
        Debug.Print cell.Value
        Debug.Print cell.Count
            If IsEmpty(cell) = True Then
                Exit For
            Else
             'Set itm = cell
                 c.Add cell.Value
             End If
     Next
    Set Test2 = c
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM