excel 排除范围中的特定行

z31licg0  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(220)

我想从A1:B5中排除A2:B2,并将其存储为一个范围,以便以后使用。我有下面的代码,它没有返回错误,但似乎没有在范围中存储任何内容。

Sub ExcludeRange()
    Dim rng As Range
    Dim newRng As Range
    
    Set rng = Sheets("Sheet1").Range("A1:B5") 'set the range you want to work with
    Set newRng = rng.Offset(2, 0).Resize(rng.Rows.Count - 1, _
                                               rng.Columns.Count)
                                               
   Sheets("Sheet1").Range("C1").Value = newRng
End Sub
chhkpiq4

chhkpiq41#

我想从A1:B5中排除A2:B2
然后简单地执行Set newRng = Range("A1:B1, A3:B5")
工作表(“Sheet1”)。范围(“C1”)。值=新范围
你似乎想粘贴一个(可能的)不连续的范围到一个“连续的”一个给定的右上角单元格
必须循环Range对象的Areas属性,以便处理它所包含的所有“子范围”
如下所示:

Sub CopyRangeValue(rangeToPaste As Range, targetCel As Range)

        With targetCel 'reference the upper-right cel of the pasted range
        
            Dim rowOffset As Long
                rowOffset = 0 

                Dim area As Range
                    For Each area In rangeToPaste.Areas ' loop through all the "sub-Ranges" the range to paste is made of
                        .Offset(rowOffset).Resize(area.Rows.Count, area.Columns.Count).Value = area.Value ' paste the current continuous "sub-Range" to the proper target cell

                        rowOffset = rowOffset + area.Rows.Count ' update the paste offset from the target cel
                    Next                    
        End With

End Sub

Sub ExcludeRange()

    Dim newRng As Range
    
    With Sheets("Sheet1")
        Set newRng = .Range("A1:B1, A3:B5")
        
        CopyRangeValue newRng, .Range("K1")                
    End With
   
End Sub

相关问题