逐行抓取数据的第一个单元格

Excel数据

该图像是我正在玩的Excel数据。 我将在稍后附上我的代码。 但是我试图用列AE中每行的第一个find的单元格填充H列。 防爆。 对于第1行应该find“B”并将其放置到H,第2行应该有“C”的地方,以“H”,所以第3行“是”到H,第4行“一”到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 

任何帮助是极大的赞赏。

如果这是作为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 as =findvalue(A2:E2) ,并且具有不需要标记为Volatile的优点。 (每当在工作表上发生任何变化时,必须重新计算“易失”函数。)


PS我强烈build议您使用Excel公式代替(例如Scott的答案中的那个) – 为什么在Excel已经提供了function时重新发明轮子?

公式是:

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

在这里输入图像说明

我不是由我的电脑所以不能testing它,但你可以试试这个

 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