如果单元格为空,则返回列标题

时间:2017-06-28 01:54:17

标签: excel vba excel-vba multiple-columns

Sample of the Worksheet

工作表包含大约100个列标题和超过800行。我想使用一个函数或创建一个宏来获取列标题,并在一个单独的列中汇总这些标题,用逗号分隔。

使用上面屏幕截图的第2行作为示例,标准2,标准5和标准7是空的。我想在名为“Missing”的列中显示这些缺失的条件,其值为“Criteria 2,Criteria 5,Criteria 7”。

1 个答案:

答案 0 :(得分:0)

此代码添加新工作表,并显示结果。

Sub test()
    Dim Ws As Worksheet, outWs As Worksheet
    Dim vDB, vR(), vResult()
    Dim r As Long, c As Long, i As Long, j As Long

    Set Ws = ActiveSheet
    With Ws
        r = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        c = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        vDB = .Range("a1", .Cells(r, c))
    End With
    ReDim vResult(1 To r, 1 To 4)
    For i = 1 To r
        n = 0
        For j = 1 To c
            If j < 4 Then
                vResult(i, j) = vDB(i, j)
            End If
            If IsEmpty(vDB(i, j)) Then
                n = n + 1
                ReDim Preserve vR(1 To n)
                vR(n) = vDB(1, j)
            End If
        Next j
        vResult(i, 4) = Join(vR, ",")
    Next i
    vResult(1, 4) = "Missing"
    Set outWs = Sheets.Add '<~~ your specific sheets : Sheet("your sheet name")
    With outWs
        .Range("a1").Resize(r, 4) = vResult
        .Columns.AutoFit
    End With
End Sub