2017-03-26 32 views
3

我已編碼下面的宏,它是工作時,我將值保存到立即窗口,但不知道如何填充值,用「,」分隔到一個單元格。基本上,我在一列中尋找「有效」,如果找到了,就去4個單元格左邊,並從那裏獲取信息... 你能幫忙嗎?刪除重複,連接,從頂部

Dim Active() As Variant 
Dim i 
ReDim Active(Range("G9:G24").Cells.Count) 
For Each Zelle In Range("G9:G24") 
If InStr(1, Zelle, "Active") <> 0 Then 
Active(i) = Zelle.Offset(0, -4) 
End If 
i = i + 1 
Next Zelle 

For i = LBound(Active) To UBound(Active) 
If Trim(Active(i)) <> "" Then 
    Debug.Print Active(i) 
    End If 
    Next i 
    End Sub 
+0

你可能要考慮的加入功能。 –

+0

@RichHolton Join函數是很自然的,但是'Trim(Active(i))<>「」'表明它可能有空的字段,在連接之後必須修復它們。 –

+0

@JohnColeman好點。 –

回答

1

您可以通過相應的不空白細胞所需的單元格範圍僅在C列循環大大縮短你的代碼

Dim Zelle As Range 
    Dim resultStrng As String 

    For Each Zelle In Range("G9:G24").Offset(,-4).SpecialCells(xlCellTypeConstants) '<--| loop through not blank cell in range 4 columns to the left of G9:G24 
     If InStr(1, Zelle.Offset(, 4), "Active") <> 0 And Trim(Zelle) <> "" And Instr(resultStrng, Trim(Zelle)) =0 Then resultStrng = resultStrng & Trim(Zelle) & "," '<--| update your result string whenever current cell has a character and its 4 columns to the right offset cell meets the "Active" criteria 
    Next Zelle 
    If resultStrng <> "" Then resultStrng = Left(resultStrng, Len(resultStrng) - 1) '<-- remove the last comma from 'resultStrng' 
+0

代碼正在工作,現在我試圖從數組中添加唯一的值。嘗試與另一個For循環,但不能通過這個...任何想法? – Siegfrid

+0

請參閱編輯的代碼。如果它解決了您的問題,您可能需要將答案標記爲已接受。謝謝! – user3598756

+0

謝謝,我之前錯過了此代碼... – Siegfrid

2

添加以下

然後重寫這樣的循環:

For i = LBound(Active) To UBound(Active) 
    If Trim(Active(i)) <> "" Then 
     s = s & IIf(Len(s)>0, ",", "") & trim(Active(i)) 
     End If 
Next i 

然後你就可以分配到s細胞。

+0

完美,非常感謝! – Siegfrid