复制多个范围(动态)而不选择它们

时间:2017-07-21 13:17:27

标签: vba excel-vba excel

问题

如何在不选择单元格的情况下执行单元格列表的副本? 我想要复制范围A1A5A7。 它们存储在如下字符串中:addr = "A1,A5,A7"

如果我先选择它们并复制它们,那么动作就可以了:

Range(addr).Select
Selection.Copy

当我从剪贴板粘贴时,我只有我选择的值。

另外,如果我按照建议的here执行Union Range,那么在没有选择的情况下也会有效:

Dim rng1 As Range, rng2 As Range, rng3 As Range, rngUnion As Range
Set rng1 = Range("A1")
Set rng2 = Range("A5")
Set rng3 = Range("A7")
Set rngUnion = Union(rng1,rng2,rng3)
rngUnion.Copy

但是,我不能既不先选择范围,也不在运行时知道我必须选择多少个范围。

我试过这样做:

Range(addr).Copy

但是当我执行粘贴时,它会获取A1和A7之间的所有值(基本上是A1:A7)。

如何在不选择单元格或将它们联合的情况下复制单个单元格?

背景 - 没有必要回答我猜的问题

我有一个列表框,其中有一个值列表,用户可以多选(他们可以选择第一行,第四行,第七行等)。

当他们这样做时,我构建了一个包含这些值的集合:

["value1", "value2", "value3", ... ]

这些值在电子表格中是唯一的(如果我运行Find,我只能找到一个范围)。 你可以猜到,我事先并不知道集合中会有多少值。

我需要做的是让他们复制他们的选择。因此,我根据这些值构建了一个集合:

For j = 0 To Me.longList.ListCount - 1
    If Me.longList.Selected(j) Then
        tmpColl.Add Split(Split(Me.longList.List(j), " ")(1), " ")(0) '<-- add the story ID to the collection
    End If
Next j

然后,我构建了包含多项选择地址的字符串:

For j = 1 To tmpColl.Count
    With Sheets("Stories list")
        Set rng = .Range("A1:A10000").Find(tmpColl(j), lookAt:=xlWhole)
        addr = addr & "$A$" & rng.Row & ","
    End With
Next j

addr = Left(addr, Len(addr) - 1)

1 个答案:

答案 0 :(得分:0)

这样的事情应该无需选择条目即可。它会将单元格地址拆分为一个数组,然后迭代它们以将值添加到一个新数组中以输出到工作表。

我已将值放在A1,A3,A5中,并将其移至B列。所有代码都假定这是在ActiveSheet上运行。

Option Explicit

Sub SO_Example()
    'Assign a string with the range you want to add
    Dim addStr As String: addStr = "A1,A3,A5"

    'Split the string by a comma to create an array of cells
    Dim cellArr As Variant: cellArr = Split(addStr, ",")
    Dim i As Long

    'Resize the OutArray to be as large as the number of cells to select
    Dim arrOut As Variant: ReDim arrOut(UBound(cellArr))

    'Add the items to the array
    For i = LBound(cellArr) To UBound(cellArr)
        arrOut(i) = Range(cellArr(i)).Value
    Next

    'Output to column B
    Range("B1:B" & i).Value = WorksheetFunction.Transpose(arrOut)
End Sub