如何使用VBA对每列应用验证

时间:2016-06-22 06:46:01

标签: vba excel-vba excel

我有一个包含100多列的sheet1中的数据。在sheet2中,我为每列提供了验证公式(正则表达式)。我希望在将数据粘贴到sheet3之前检查每列的验证公式,从而将数据从sheet1复制到sheet3。如果它满足公式,则复制在sheet3中并用绿色填充单元格或如果不满足复制数据到sheet3并用红色填充该单元格。Sheet1 Data Sheet2 Data Click Here for Sheet3 Data after copy

Sub test()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim wbk As Workbook
    Dim sRegex As Variant
    Dim lColumn As Long
    Dim sText As String
    Set sRegex = CreateObject("VBScript.RegExp")
    Set wb = ActiveWorkbook
    wb.Sheets("Sheet3").Activate
    lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    lColumn = wb.Sheets("Sheet3").UsedRange.Column + wb.Sheets("Sheet3").UsedRange.Columns.Count - 1
    For i = 1 To lColumn
    temp = Cells(1, i).Value
    For j = 2 To lastRow
    sText = Cells(j, i).Value
        Set wb = ActiveWorkbook
         sheetName = ActiveSheet.Name
    wb.Sheets("Sheet4").Activate
    sheetName = ActiveSheet.Name

    lRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
    For k = 2 To lRow
    temp2 = wb.Sheets("Sheet4").Cells(k, 1).Value
    If wb.Sheets("Sheet4").Cells(k, 1).Value = temp Then
   temp1 = wb.Sheets("Sheet4").Cells(k, 2).Value
    sRegex.Pattern = wb.Sheets("Sheet4").Cells(k, 2).Value
    sRegex.Global = True
     Debug.Print TestRegex(sText, sRegex)
     Else
     End If
    Next k  
    Next j
    Next i
End Sub

Function TestRegex(sInput As String, sRegex As Variant) As Boolean
    TestRegex = sRegex.test(sInput)
   ' ActiveCell.Interior.ColorIndex = 3
    Dim wb As Workbook
    Set wb = ActiveWorkbook
    wb.Sheets("Sheet3").Activate
    Cells(Selection.Row, Columns.Count).End(xlToLeft).Offset(, 1).Select
    'wb.Sheets("Sheet3").Cells(2, 9).Value = TestRegex
    ActiveCell.Value = TestRegex

End Function

1 个答案:

答案 0 :(得分:1)

我相信您知道如何复制数据,但您不知道如何使用Regex验证对象。

如果我理解正确,您将逐行复制,并且您希望根据REGEX表达式验证每一列(从行开始)。

我不太确定会有多快,但你需要做的是首先创建一个Regex对象,如下所示(我使用Late Binding,但你可以自由地将它添加到References并使用Early Binding )。

这是让你入门的东西:

Function TestRegex(sInput As String, sRegex As Variant) As Boolean
    TestRegex = sRegex.test(sInput)
End Function


Sub test()
    Dim sRegex As Variant
    Set sRegex = CreateObject("VBScript.RegExp")
        sRegex.Pattern = "^[A-Z]" 'regex of your choice
        sRegex.Global = True

    Dim sText As String
        sText = "abc123"

    Debug.Print TestRegex(sText, sRegex)
End Sub