2017-10-17 42 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 
相關問題