将具有相应ID号的行复制到其他工作表中

时间:2019-07-10 11:25:05

标签: excel vba userform

我有一个用户窗体,可让您键入一个ID号,我希望将具有相应ID号的行复制到另一个未对齐单元格的工作表中。

我尝试使用数组作为数据的目标,但运行时它什么也没做。我知道我可以这样做,将每个单元格编码到另一个单元格,但是我认为使用数组存储要复制的数据是可行的,现在我需要知道如何将所有目标单元格放在一个单元格中变量并在那里复制数据

Dim ws As Worksheet
Set ws = Sheets("Arkiv")
Dim DN As Worksheet
Set DN = Sheets("DN")

idRow = Sheets("Arkiv").Columns("A:A").Find(what:=IDnum).Row
IDnum = TextBox1.Text

'Dim shipFrom As Range
    'Set shipFrom = Sheets("Arkiv").Range("B" & idRow)

Dim goTo1 As Variant
goTo1 = Array(DN.Range("D9"), DN.Range("E9"), DN.Range("I9"), DN.Range("C20"), DN.Range("D20"), DN.Range("E45"), DN.Range("G20"), DN.Range("H20"), DN.Range("I20"))

Dim data As Variant
data = Array(ws.Range("B" & idRow), ws.Range("C" & idRow), ws.Range("D" & idRow), ws.Range("E" & idRow), ws.Range("F" & idRow), ws.Range("G" & idRow), ws.Range("H" & idRow), ws.Range("I" & idRow))

goTo1 = data

我希望将变量“ data”中的数据按照我将它们放入数组的相应顺序复制到“ goTo1”变量内部的单元格中。enter code here

2 个答案:

答案 0 :(得分:1)

  1. 如果使用find方法,请始终指定LookAt参数,否则VBA将使用上次使用的内容(由用户或VBA使用)。

  2. 您需要循环浏览地址,然后一个一个地复制它们。您不能一次复制非连续范围。

所以这样的事情应该起作用。

Option Explicit

Public Sub CopyRanges()
    Dim wsSource As Worksheet
    Set wsSource = ThisWorkbook.Worksheets("Arkiv")
    Dim wsDestination As Worksheet
    Set wsDestination = ThisWorkbook.Worksheets("DN")

    Dim IDnum As String
    IDnum = TextBox1.Text

    Dim idRow As Long
    idRow = wsSource.Columns("A:A").Find(What:=IDnum, LookAt:=xlWhole).Row

    Dim SourceAddresses() As Variant
    SourceAddresses = Array("B" & idRow, "C" & idRow, "D" & idRow, "E" & idRow, "F" & idRow, "G" & idRow, "H" & idRow, "I" & idRow)

    Dim DestinationAddresses() As Variant
    DestinationAddresses = Array("D9", "E9", "I9", "C20", "D20", "E45", "G20", "H20", "I20") 

    If UBound(SourceAddresses) <> UBound(DestinationAddresses) Then
        MsgBox "Amount of source addresses must be the same amount as destination addresses"
        Exit Sub
    End If     

    Dim i As Long
    For i = LBound(SourceAddresses) To UBound(SourceAddresses)
        wsDestination.Range(DestinationAddresses(i)).Value = wsSource.Range(SourceAddresses(i)).Value
    Next i
End Sub

答案 1 :(得分:1)

尝试一下:

gradle.properties