Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

excel - Incorrect result from CurrentRegion when used in a function called from a cell

I'm trying to write a VBA function to be called from a cell. In this function I need to use the CurrentRegion property but it returns an unexpected result.

The function:

Function GetVarRange() As String

    Dim rngRangeToLeft As Range, wks As Worksheet
    Set wks = Application.Caller.Worksheet
    Set rngRangeToLeft = wks.Range("A1").CurrentRegion

    GetVarRange = rngRangeToLeft.Address

End Function

The result I get in the cell is $A$1.

There are values in A1, and all around it, the CurrentRegion is actually A1:AD618 and this is the result I get when I access the property within the code editor (not in this function) and when I press ctrl+A when A1 is selected.

Any ideas anyone?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CurrentRegion does not work correctly in UDF()'s called from worksheet cells. I have also found problems with FindNext and SpecialCells.

Called from a Sub, it is a different story:

Function GetVarRange(rng) As String
    Dim rngRangeToLeft As Range, wks As Worksheet
    Set rngRangeToLeft = rng.CurrentRegion
    GetVarRange = rngRangeToLeft.Address
End Function

Sub MAIN()
MsgBox GetVarRange(Range("A1"))
End Sub

appears to work just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...