Excel VBA function works in Visual Basic, but fails in Worksheet

后端 未结 2 1611
抹茶落季
抹茶落季 2020-12-04 00:43

I\'m trying to build a 2D array of data using \"CurrentRegion\".

Function ProcessData()
Dim dataList()
dataList = Range(\"A1\").CurrentRegion
\' TODO Process         


        
相关标签:
2条回答
  • 2020-12-04 01:25

    I've just encountered this Q&A having the same problem. I think there is a kind of bug for using CurrentRegion within UDF and the reason is not as Peter suggest in his answer.

    Compare these two function:

    Function GetAddressOfColumn(TopCell As Range)
        GetAddressOfColumn = TopCell.CurrentRegion.Address
    End Function
    
    
    Function GetAddressOfColumnOK(TopCell As Range)
        GetAddressOfColumnOK = Range(TopCell, TopCell.End(xlDown)).Address
    End Function
    

    Both function use different kind of range references. If Peter were right both should return false result. So, look at the data range below and the result of both function. As you can see second function result is as expected and correct.

    enter image description here

    0 讨论(0)
  • 2020-12-04 01:28

    If you call a Function from an Excel cell (i.e. as an User-Defined-Function/UDF), you can only access the ranges that are handed to the function via parameters. Any access to other ranges (and .CurrentRegion is a range) will result in a "Circular Reference" potential cancellation of the execution.

    Also, in a UDF you cannot modify anything on the worksheet - but only return the result of function!

    For further details, check out this link.

    0 讨论(0)
提交回复
热议问题