2017-02-14 61 views
0

Excel Data按列逐行抓取第一個數據單元格

該圖像適用於我隨身攜帶的excel數據。我將在稍後附上我的代碼。但是我試圖用列A-E中每行的第一個找到的單元格填充H列。防爆。對於第1行,應該找到「B」並將其放置到H,第2行應該將「c」放置到「H」,並且第3行「是」到第4行「a」到H.

我不能爲我的生活弄清楚這一點。 VBA從來就不是我最強的套裝,現在我已經玩了兩天了。這是我的代碼。

Function findValue() As String 
Dim rng As Range 
Dim row As Range 
Dim cell As Range 
Dim val As String 

' Sets range of 5 columns to search in by column 
Set rng = Range("A:E")        

' searches through count of rows 
For i = 2 To Range("A" & Rows.Count).End(xlUp).row 
For Each cell In rng.Cells(i) 
    If IsEmpty(cell) = True Then 
    MsgBox cell 
    MsgBox i 
    Else 
     'MsgBox Range.(cell & i).Value 
     findValue = cell 
     Set rng = Range("A:E") 
     Exit For 
    End If 
Next cell 
Next i 
End Function 

任何幫助,非常感謝。

+1

這是可以做到的一個公式,如果你有興趣。 –

+0

Vlookup公式? – DanBrennan33

+0

希望你會接受斯科特提出的使用公式的建議,但是,如果沒有,這是否意味着是一個函數或子程序?即你試圖運行函數來獲取一個值(對於一行嗎?)還是你想要運行一個子程序來一次處理所有的行? – YowE3K

回答

0

如果這是打算作爲一個UDF,我認爲下面的代碼是你所追求的:

Function findValue() As String 
    Application.Volatile = True 
    Dim r As Long 
    Dim c As Long 
    r = Application.Caller.Row 
    For c = 1 To 5 
     If Not IsEmpty(Cells(r, c)) Then 
      findValue = Cells(r, c).Value 
      Exit Function 
     End If 
    Next 
    findValue = "" 
End Function 

的另一種方法,在這裏傳遞的範圍內進行檢查,而不是僅僅檢查當前行,將是:

Function findValue(rng As Range) As String 
    Dim c As Range 
    For Each c In rng 
     If Not IsEmpty(c) Then 
      findValue = c.Value 
      Exit Function 
     End If 
    Next 
    findValue = "" 
End Function 

這然後可以在細胞H2=findvalue(A2:E2)使用,並且有它不需要被標記優點。 (每當工作表上的任何變化都必須重新計算「揮發性」功能。)


P.S.我強烈建議您改用Excel公式(例如Scott's answer中的那個) - 爲什麼在Excel已經提供了功能時重新發明輪子?

+0

謝謝@ YowE3K這個工作完美..我需要在VBA變得更好。 – DanBrennan33

0

我不是我的PC所以無法測試它,但你可以試試這個

Sub FindValue() 
    Dim myRow As Range 

    ' Sets Range of 5 columns to search in by column 
    Set rng = Intersect(Range("A:E"),ActiveSheet.UsedRange) 

    ' searches through count of rows 
    For each myRow in rng.Rows 
     Cells(myRow.Row, "H").Value = myRow.Cells.SpecialCells(xlCellTypeConstants).Cells(1) 
    Next 
End Sub 
1

其計算公式爲:

=INDEX(A1:E1,AGGREGATE(15,6,COLUMN(A1:E1)/(A1:E1<>""),1)) 

enter image description here

相關問題