仅当使用宏

时间:2016-07-25 16:54:45

标签: excel vba excel-vba macros

我创建了一个简单的宏来过滤数据并复制并将其添加到最后一行之后的特定工作表[ISRisks]。但我意识到,我不确定如何检查[ISRisks]表中是否已存在数据!请有人帮忙 - [ISRisks]中的列a包含要检查的唯一RISKID字段。 这就是我到目前为止所做的:

  Sub ISRISKCOPY()
        '
        Dim lMaxRows  As Long
        Dim ws As Worksheet
        Dim rng As Range
        Dim LR As Long
        Dim rTable As Range

     For Each ws In ActiveWorkbook.Worksheets
                If (ws.Name <> "ISRisks") And (ws.Name <> "Closed Risks") And (ws.Name <> "Risk Grading Matrix ") And (ws.Name <> "Sheet1") And (ws.Name <> "Sheet2") Then
            Application.DisplayAlerts = False

            With ws

             If .FilterMode Then .AutoFilterMode = False
            Sheets(ws.Name).Range("$A$2:$W$2").AutoFilter Field:=5, Criteria1:=Array("IS", "IS - Information Security"), Operator:=xlFilterValues
            Set rTable = Sheets(ws.Name).AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible)
            rTable.Copy
            lMaxRows = Sheets("ISRisks").Cells(Rows.Count, "a").End(xlUp).Row

             Range("a" & lMaxRows + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

            End With

            Else
                End If

            Next ws

            'sorting unique id column
            Sheets("ISRisks").Range("A1").Select
            ActiveWorkbook.Worksheets("ISRisks").Sort.SortFields.Clear
            ActiveWorkbook.Worksheets("ISRisks").Sort.SortFields.Add Key:=Range("A1"), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            With ActiveWorkbook.Worksheets("ISRisks").Sort
            .SetRange Range("A2:A10000")
            .Header = xlNo

.MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

Application.DisplayAlerts = True
    End Sub

1 个答案:

答案 0 :(得分:0)

您可以使用此代码搜索范围并确定值是否存在。

With Sheets("Sheet1").Range("A:A")
    Set Rng = .Find(What:=FindString, _
                    After:=.Cells(.Cells.Count), _
                    LookIn:=xlValues, _
                    LookAt:=xlWhole, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False)
    If Not Rng Is Nothing Then
        'Do This If Found
    Else
        'Do This If Not Found
    End If
End With

您需要设置要使用的工作表,要搜索的范围,并将FindString替换为您要检查的变量。 if语句中的部分是您可以根据查找或不查找执行操作的位置(如果未找到则粘贴)。如果您不需要执行操作,也可以重做以缩短它。

上面的例子被发现here.