繁体   English   中英

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

[英]Grab first cell of data in row by column

Excel数据

该图像用于我正在玩的Excel数据。 稍后我将附加我的代码。 但是我试图用列AE中每一行的第一个找到的单元格填充列H。 例如 对于第1行,应该找到“ B”并将其放置在H上,第2行应该将“ c”放置在“ H”上,依此类推,第3行“ is”到H,第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

任何帮助是极大的赞赏。

公式为:

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

在此处输入图片说明

如果打算将其用作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) ,并具有不需要标记为Volatile的优点。 (每次在工作表上进行任何更改时,都必须重新计算“可变”功能。)


PS我强烈建议您改用Excel公式(例如Scott的答案中的公式)-当Excel已经提供功能时,为什么要重新发明轮子?

我不在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM