Excel VBA:将项目从一个数组移动到另一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10120606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:55:42  来源:igfitidea点击:

Excel VBA: Move items from one array to another array

excel-vbavbaexcel

提问by ExternalUse

I'm trying to speed up an application that is designed to assign human resources to locations, using listboxes that are bound to ranges. That works quite well - the ugly part is moving items from one data range to one or more ranges using find, copy & paste.

我正在尝试使用绑定到范围的列表框来加速一个旨在将人力资源分配到位置的应用程序。这很有效 - 丑陋的部分是使用查找、复制和粘贴将项目从一个数据范围移动到一个或多个范围。

I could gain great speed by using a function to print arrays to ranges when I retrieve the data from webservices, but I couldn't figure out how to replace the find/cut/paste logic yet.

当我从网络服务中检索数据时,我可以通过使用一个函数将数组打印到范围来获得极大的速度,但我还无法弄清楚如何替换查找/剪切/粘贴逻辑。

I have now updated my previous post to include my latest tries. In a way that now works as intended, but it surely does not look smart:

我现在更新了我以前的帖子,以包括我最近的尝试。以现在按预期工作的方式,但它看起来肯定不聪明:

Updated sample

更新样本

The ranges look like this (data in Col B-E is not relevant, A contains the key). Day0_lbUsers is A1:E5, Day1_lbUsers is A28:E30.

范围看起来像这样(Col BE 中的数据不相关,A 包含键)。Day0_lbUsers 是 A1:E5,Day1_lbUsers 是 A28:E30。

        A       B       C       D       E
1       15      Foo     Bar     Bas     Nono
2       18      Foo     Bar     Bas     Nono
3       19      Foo     Bar     Bas     Nono
4       196     Foo     Bar     Bas     Nono
5       33      Foo     Bar     Bas     Nono
...
28      32      Foo     Bar     Bas     Nono
29      46      Foo     Bar     Bas     Nono
30      52      Foo     Bar     Bas     Nono

In this example, I want to move the row with the key 18 from Day0_lbUsers to Day1_lbUsers. In the sample, I have hardcoded the source and not written back to the ranges, but that's not the hard part. I'm rather interested whether there is a better way to transfer the arrays contents.

在此示例中,我想将键为 18 的行从 Day0_lbUsers 移动到 Day1_lbUsers。在示例中,我对源代码进行了硬编码并且没有写回范围,但这不是难点。我很感兴趣是否有更好的方法来传输数组内容。

Sub TestRemoveFromArray()
    Dim vSourceArray() As Variant ' source
    Dim vNewSourceArray() As Variant ' source, one key removed
    Dim vTargetArray() As Variant ' target
    Dim vNewTargetArray() As Variant ' target, one item added
    Dim rowSearch As Long, row As Long, col As Long, search As Long, blnFound As Boolean
    search = 18
    vSourceArray = shData.Names("Day0_lbUsers").RefersToRange.Value2 ' 27 rows, 5 columns, key in col 1

    ' loop source to find the row that contains the search key
    For rowSearch = LBound(vSourceArray) To UBound(vSourceArray)
        ' look into col 1 for the key
        If vSourceArray(rowSearch, 1) = search Then
            blnFound = True
            Exit For
        End If
    Next rowSearch

    If Not blnFound Then
        Exit Sub
    End If
    ' we've found the row, so let's get the target
    vTargetArray = shData.Names("Day1_lbUsers").RefersToRange.Value2
    ' a1 needs to be 1 short of a, b1 must be b +1
    ReDim vNewSourceArray(LBound(vSourceArray) To UBound(vSourceArray) - 1, 1 To 5)
    ReDim vNewTargetArray(LBound(vTargetArray) To UBound(vTargetArray) + 1, 1 To 5)

    ' copy original target to new target
    For row = LBound(vTargetArray) To UBound(vTargetArray)
        For col = LBound(vTargetArray, 2) To UBound(vTargetArray, 2)
            vNewTargetArray(row, col) = vTargetArray(row, col)
        Next col
    Next row
    ' reset blnFound
    blnFound = False
    For row = LBound(vSourceArray) To UBound(vSourceArray)
        If row = rowSearch Then
            For col = LBound(vSourceArray, 2) To UBound(vSourceArray, 2)
                vNewTargetArray(UBound(vNewTargetArray), col) = vSourceArray(row, col)
            Next col
            blnFound = True
        Else
            For col = LBound(vSourceArray, 2) To UBound(vSourceArray, 2)
                ' if blnFound was found before, write to the key -1
                vNewSourceArray(IIf(blnFound, row - 1, row), col) = vSourceArray(row, col)
            Next col
        End If
NextRow:
    Next row

    'assign new arrays (return later)
    vSourceArray = vNewSourceArray
    Erase vNewSourceArray
    vTargetArray = vNewTargetArray
    Erase vNewTargetArray

End Sub

original post, out-of-date

原帖,已过期

All the data ranges have the same number of columns (5) and are named. This is what I have so far; at some point I had to stop programming and use pseudo-code instead to illustrate. The source and target arrays are created with e.g.

所有数据范围都具有相同数量的列 (5) 并已命名。这是我到目前为止所拥有的;在某些时候,我不得不停止编程并使用伪代码来进行说明。源和目标数组是用例如创建的

vSourceArray = shData.Names("Day0_A").RefersToRange.Value2 ' (1 to 27, 1 to 5)

Private Function MoveUserId(ByRef vSourceArray() As Variant, ByRef vTargetArray() As Variant, lngUserId As Long) As Boolean
    Dim lSearchKey As Long, blnFound As Boolean, col As Long
    Dim vTempArray() As Variant, vRow() As Variant
    For lSearchKey = LBound(vSourceArray) To UBound(vSourceArray)
        If vSourceArray(lSearchKey, 1) = lngUserId Then
            blnFound = True
            Exit For
        End If
    Next lSearchKey
    If blnFound = False Then
        MoveUserId = False
        Exit Function
    End If
    ' extract the row found
    ReDim vRow(1 To 1) As Variant
    vRow(1) = Application.WorksheetFunction.index(vSourceArray, lSearchKey)
    ' now, add an item to targetarray and populate using a function from http://www.cpearson.com
    vTargetArray = CombineTwoDArrays(vTargetArray, vRow) ' does not work

    ' now delete the key in source array
    ' help!  
End Function

Apart from the search function, this does not really work. The first thing would be to extract a row and copy it to a new, re-dimensioned target array. Easiest would be to redim the target to elements + 1; and then do something like (pseudo-code) pushing it to the end:

除了搜索功能之外,这并没有真正起作用。第一件事是提取一行并将其复制到一个新的、重新定义大小的目标数组。最简单的方法是将目标重新调整为元素 + 1;然后做一些类似(伪代码)将它推到最后的事情:

vTargetArray(addedIndex) = vSourceArray(searchIndex)

The second thing which does not appear to be easy is deleting a key, but I haven't investigates web resources that much yet.

第二件看起来并不容易的事情是删除一个密钥,但我还没有对网络资源进行太多调查。

I would very much appreciate if you could show me the light. Thanks in advance, Stefan

如果你能给我看灯,我将不胜感激。提前致谢,斯蒂芬

回答by Siddharth Rout

We don't need a temp array to do the combining but since you are using a temp array vRow, let me also use one to illustrate how it works :) See this example

我们不需要临时数组来进行组合,但由于您使用的是临时数组vRow,让我也用一个来说明它是如何工作的:) 看这个例子

Sub Sample()
    Dim Ar1(), Ar2(), Ar3()
    Dim i As Integer

    Ar1() = Array("A", "B", "C", "D")
    Ar2() = Array("1", "2", "3", "4")

    ReDim Preserve Ar3(1)

    Ar3(1) = Ar1(1)

    'Debug.Print "Ar3 >> "; Ar3(1)

    ReDim Preserve Ar2(UBound(Ar2) + 1)

    Ar2(UBound(Ar2)) = Ar3(1)

    For i = 0 To UBound(Ar2)
        Debug.Print "Ar2 >> "; Ar2(i)
    Next i
End Sub

HTH

HTH

enter image description here

在此处输入图片说明

FOLLOW UP

跟进

If you'd like to have a go, you could put some data in e.g. Sheet1 A1:E5, and A6:E8 or so, and create vSourceArray = range("A1:E5").Value2 and vTargetArray() = Range("A6:E8").Value2 and try to move data in between. That gives you similar arrays to work with as I have them. – ExternalUse 1 hour ago

如果你想试一试,你可以把一些数据放在例如 Sheet1 A1:E5 和 A6:E8 左右,然后创建 vSourceArray = range("A1:E5").Value2 和 vTargetArray() = Range( "A6:E8").Value2 并尝试在两者之间移动数据。这为您提供了类似的数组,就像我拥有它们一样。– 外部使用 1 小时前

I did as you suggested but took a slightly different way to achieve what you want. Also for testing purpose, as commented in the code below I have taken lSearchKeyas 2

我按照你的建议做了,但采取了稍微不同的方式来实现你想要的。同样出于测试目的,如下面的代码中所述,我已将其lSearchKey视为 2

CODE:

代码

Option Explicit

Sub Sample()
    Dim Ar1() As String, Ar2() As String, Ar3() As String
    Dim Rng1 As Range, Rng2 As Range
    Dim ws As Worksheet
    Dim i As Long, j As Long

    Set ws = Sheets("Sheet1")

    With ws
        Set Rng1 = .Range("A1:E5")
        Set Rng2 = .Range("A6:E8")

        '~~> Redim Ar2 and Ar3 arrays
        ReDim Ar2(Rng2.Rows.Count, Rng2.Columns.Count)
        ReDim Ar3(0, Rng2.Columns.Count)

        '~~> Store Range 2 in Ar2
        For i = 0 To Rng2.Rows.Count - 1
            For j = 0 To Rng2.Columns.Count - 1
                Ar2(i, j) = Rng2.Cells(i + 1, j + 1)
                'Debug.Print Ar2(i, j)
            Next j
        Next i

        '~~> Manually setting the Search Key for testing purpose
        Dim lSearchKey As Long
        lSearchKey = 2

        '~~> Adding the relevant data from Ar2 to Ar3
        For i = 0 To Rng2.Columns.Count - 1
            Ar3(0, i) = Ar2(lSearchKey - 1, i)
            'Debug.Print Ar3(1, i)
        Next

        '~~> Redim the 1st Array
        ReDim Preserve Ar1(Rng1.Rows.Count, Rng1.Columns.Count)

        '~~> Store Range 1 in Ar1
        For i = 0 To Rng1.Rows.Count - 1
            For j = 0 To Rng1.Columns.Count - 1
                Ar1(i, j) = Rng1.Cells(i + 1, j + 1)
                'Debug.Print Ar1(i, j)
            Next j
        Next i

        '~~> Store the Ar3 into Ar1
        For i = 0 To Rng2.Columns.Count - 1
            Ar1(UBound(Ar1), i) = Ar3(0, i)
            Debug.Print ">>"; Ar1(UBound(Ar1), i)
        Next i
    End With
End Sub

SNAPSHOT

快照

enter image description here

在此处输入图片说明