2017-10-17 48 views
0

我在我的表格中搜索某个值的范围,当找到这些值中的任何一个时,我想将该行的A列中的值添加到数组中,只添加数组中不存在的值。一旦范围被搜索,我想打印数组到指定的单元格在工作表中的2个不同的列。将值添加到动态数组,然后打印到指定的单元格

这里是我到目前为止的代码:

Dim Ws As Worksheet 
Set Ws = Sheets("Sheet1") 
Dim Leave() As Variant, Join() As Variant 
Dim LastCol As Integer, LastRow As Integer, i As Integer, Z As Integer 
Dim J As Long, L As Long 

With Sheets("Sheet1") 
    'Find Last Col 
    LastCol = Sheets("Sheet1").Cells(3, Columns.Count).End(xlToLeft).Column 

    'Find last Row 
    LastRow = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row 
    LastRow = LastRow - 1 

    'ReDim Leave(1 To (LastRow - 1), LastCol) 
    'ReDim Join(1 To (LastRow - 1), LastCol) 

    For i = 5 To LastCol 
     For Z = 4 To LastRow 

      If Sheets("Sheet1").Cells(Z, i).Value = "0" Then 
       Leave(L) = Ws.Cells(Z, 1).Value 

      ElseIf Sheets("Sheet1").Cells(Z, i).Value = "-2" Then 
       Join(J) = Ws.Cells(Z, 1).Value 

      End If 
     Next Z 
    Next i 
    'Print array 

End With 

感谢提前任何指针/帮助!

+1

在匆忙作出详细的看看你的代码现在。但要提两件事:1)不要使用Join作为变量,是一个保留字; 2)检查值是否已经在数组中,请看[这里](https://stackoverflow.com/a/34754113/1726522)(最后一个函数)。 – CMArg

+0

您遇到什么问题?我可以告诉你,当'Leave'和'Join'被更新时(即Leave(L)= Ws.Cells(Z,1)),你会想增加'L'和'J'值。 L = L + 1'),或者每次迭代都会覆盖'Leave(0)'和'Join(0)'。 –

+0

是否有任何东西阻止您使用字典或集合对象而不是数组? – KacireeSoftware

回答

0

我相信这个程序可以完成你正在寻找的东西。您将需要修改您正在搜索的范围和目标表的信息,但该程序的肉是在这里:

Sub abc_Dictionary() 
    Dim oWS As Worksheet 
    Dim RangeToSearch As Range 
    Dim myCell As Range 
    Dim UniqueDict As Object 

    Set oWS = Worksheets("Sheet1") 
    Set RangeToSearch = oWS.Range("B1:B26") 'You can set this dynamically however you wish 
    Set UniqueDict = CreateObject("Scripting.Dictionary") 

    'Now we search the range for the given values. 
    For Each myCell In RangeToSearch 
     If (myCell.Text = "0" Or myCell.Text = "-2") And Not UniqueDict.exists(oWS.Range("A" & myCell.Row).Text) Then 
      UniqueDict.Add oWS.Range("A" & myCell.Row).Text, oWS.Range("A" & myCell.Row).Text 
     End If 
    Next 

    'Now we have a dictionary object with the unique values of column a 
    'So we just iterate and dump into Sheet2 
    Dim d As Variant 
    Dim Val As Variant 
    Dim DestRow As Integer 

    DestRow = 1 'This is the first row of data we will use on Sheet 2 
    d = UniqueDict.Items 
    For Each Val In d 
     Worksheets("Sheet2").Range("A" & DestRow).Value = Val 
     DestRow = DestRow + 1 
    Next 



    Set UniqueDict = Nothing 
    Set RangeToSearch = Nothing 
    Set oWS = Nothing 
End Sub 
相关问题