简体   繁体   中英

Excel VBA New range from selection

I'm working with a complex UserDefined function that works only with a single and contiguous range of data. Therfore I would like to create a function, which for a given range, returns me a new range emptied of blank cells, which will serve as input for the initial function.

Here's what what I have unsuccessfuly done so far:

Public Function NewRange(rng) As Range

    rng.SpecialCells(xlCellTypeConstants).Select
    rng.SpecialCells(xlCellTypeFormulas).Select
    rng = Union(rng.SpecialCells(xlCellTypeConstants), _
      rng.SpecialCells(xlCellTypeFormulas)).Select
Set NewRange = rng
End Function

Could you help me please in solving it?

Public Function NewRange(ByRef rng As Range) As Range
    Dim nrC As Range, nrF As Range

    If Len(rng.Value2) = 0 Then Set rng = rng.Parent.UsedRange.Cells(1, 1)
    Set rng = rng.CurrentRegion

    On Error Resume Next
    Set nrC = rng.SpecialCells(xlCellTypeConstants)
    Set nrF = rng.SpecialCells(xlCellTypeFormulas)

    Select Case True
        Case Not nrC Is Nothing And Not nrF Is Nothing: Set NewRange = Union(nrC, nrF)
        Case Not nrC Is Nothing:                        Set NewRange = nrC
        Case Not nrF Is Nothing:                        Set NewRange = nrF
    End Select
    If NewRange Is Nothing Then Set NewRange = rng.Parent.Cells(1)
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