在Excel VBA中如何保存通过我的宏所做的选择?

时间:2013-12-03 00:29:15

标签: excel vba excel-vba

我想选择第5行范围内包含单词“TEST”的每一列,然后选择下面的单元格到一定数量。 我可以找到并选择我想要的范围,当我完成时我不能完成所有选择,我想要它们以便我可以进行一些条件格式化。

Public Sub Macro1()

Dim n As Integer
n = 5

For Each c In Worksheets("Sheet1").Range("E5:UM5").Cells

    If InStr(1, "TEST", "TEST") Then
        Range(Cells(6, n), Cells(48, n)).Select
        n = n + 1
    End If

Next

End Sub

您认为数组会帮助我保留数据然后选择吗?

3 个答案:

答案 0 :(得分:1)

以下代码是从用户 ooo 回复here修改的。

你需要选择细胞吗?在vba中,你可以做大多数事情而无需实际选择单元格,这样可以更快,更不容易出错。

如果你确实需要选择单元格,我会建立范围,然后在结尾处一次选择它。

戈登

Sub test()
Dim rng1 As Range
Dim rng2 As Range
Dim newRng As Range

    With Sheet1

        Set rng1 = .Range("A1:A3")
        Set rng2 = .Range("C3:C5")

        Set newRng = Union(rng1, rng2)

        set rng2 = .range("E5:E7")

        set newRng = Union(newRng,rng2)
        newrng.select

    End With
End Sub

应用于您的代码

Public Sub Macro1()

Dim n As Integer
dim rng as range
n = 5

For Each c In Worksheets("Sheet1").Range("E5:UM5").Cells

    If InStr(1, "TEST", "TEST") Then
        If rng Is Nothing Then 
            Set rng = Range(Cells(6, n), Cells(48, n)) 
        else
            set rng = union(rng, range(cells(6,n),cells(48,n)))
        end if
        n = n + 1
    End If    
Next

rng.select

End Sub

答案 1 :(得分:1)

Public Sub Macro1()

Dim n As Integer, rng as Range, sht as WorkSheet

Set sht = Worksheets("Sheet1")

For Each c In sht.Range("E5:UM5").Cells

    If  c.value Like "*TEST*" Then

        If rng is nothing then      
            Set rng = c.offset(1,0).Resize(43,1)
        else
            Set rng = Application.union(rng, c.offset(1,0).Resize(43,1))
        end if

    End If

Next

rng.select

End Sub

答案 2 :(得分:1)

Public Sub Macro1()

Dim c As Range, rng As Range, ws As Worksheet

Set ws = Worksheets("Sheet1")

For Each c In ws.Range("E5:UM5").Cells

    If InStr(c, "TEST") Then

        If rng Is Nothing Then
            Set rng = c
        Else
            Set rng = Application.Union(rng, c)
        End If

    End If

Next

If Not rng Is Nothing Then
    rng.Select
    Debug.Print rng.Address
Else
    Debug.Print "Not found"
End If

End Sub