seventeen珉奎周洁琼:VBA复制非连续选择区域 | 水文工具集

来源:百度文库 编辑:中财网 时间:2024/05/09 12:08:47

Excel中你是无法多重选定区域进行复制的,于是水文工具集介绍一个采用VBA宏过程突破这一限制来完成对非连续选择区域的复制粘贴,具体VBA实现代码如下:

01.'================================ 02.' VBA复制非连续选择区域 03.' 04.' http://www.cnhup.com 05.'================================ 06.Sub HUP_CopyMultipleSelection() 07.    Dim SelAreas() As Range 08.    Dim PasteRange As Range 09.    Dim UpperLeft As Range 10.    Dim NumAreas As Long, i As Long11.    Dim TopRow As Long, LeftCol As Long12.    Dim RowOffset As Long, ColOffset As Long13.  14.    If TypeName(Selection) <> "Range" Then Exit Sub15.  16.'   Store the areas as separate Range objects 17.    NumAreas = Selection.Areas.Count 18.    ReDim SelAreas(1 To NumAreas) 19.    For i = 1 To NumAreas 20.        Set SelAreas(i) = Selection.Areas(i) 21.    Next22.  23.'   Determine the upper-left cell in the multiple selection 24.    TopRow = ActiveSheet.Rows.Count 25.    LeftCol = ActiveSheet.Columns.Count 26.    For i = 1 To NumAreas 27.        If SelAreas(i).Row < TopRow Then TopRow = SelAreas(i).Row 28.        If SelAreas(i).Column < LeftCol Then LeftCol = SelAreas(i).Column 29.    Next30.    Set UpperLeft = Cells(TopRow, LeftCol) 31.  32.'   Get the paste address 33.    On Error Resume Next34.    Set PasteRange = Application.InputBox _ 35.      (Prompt:="指定粘贴目标左上角单元格:", _ 36.      Title:="Copy Multiple Selection www.CnHUP.com", _ 37.      Type:=8) 38.    On Error GoTo 0 39.'   Exit if canceled 40.    If TypeName(PasteRange) <> "Range" Then Exit Sub41.  42.'   Make sure only the upper-left cell is used 43.    Set PasteRange = PasteRange.Range("A1") 44.  45.'   Copy and paste each area 46.    For i = 1 To NumAreas 47.        RowOffset = SelAreas(i).Row - TopRow 48.        ColOffset = SelAreas(i).Column - LeftCol 49.        SelAreas(i).Copy PasteRange.Offset(RowOffset, ColOffset) 50.    Next i 51.End Sub