时间:2017-10-23 11:50:01

标签: excel vba excel-vba

我想根据标题而不是列号来测试各个列。如果所选列的任何单元格包含文本,特殊字符和字母数字值,则宏应将单元格地址弹出为错误。

这是我的代码:

Sub Test()
     Dim LastRow As Long, i As Long

    LastRow1 = Cells(Rows.Count, "C").End(xlUp).Row ' here instead of mentioning C or D i want to mention Column Header
    LastRow2 = Cells(Rows.Count, "D").End(xlUp).Row  ' here instead of mentioning C or D i want to mention Column Header

    For i = 2 To LastRow
        If Range("C" & i).Value = a-z or "SpecialCharacters"Then 
            msgbox "Error in " & i & "Row of C"
        elseif Range("D" & i).Value = a-z or "SpecialCharacters"Then 
            msgbox "Error in " & i & "Row of D"
        else
            Msgbox "No error in column C" ' instead of C it should show Header name 
            Msgbox "No error in column D"  ' instead of C it should show Header name   
        end if

enter image description here

感谢您的时间和努力。请不要使用任何功能来执行此操作,因为我还有其他代码可以运行并使用功能会变得有点困难。这里c2,c3,c4,列c的最后一个单元格和所有空白不应被视为错误。

1 个答案:

答案 0 :(得分:0)

您可以使用“查找”找到标题名称,如下所示。在下面的示例中,我假设标题位于第1行:

    lngCheckCol = Range("1:1").Find("HeaderName", , , xlWhole).Column
    LastRow1 = Cells(Rows.Count, lngCheckCol).END(xlUp).Row