2

我有一个单元格地址的一维数组(单元格可能不相邻)。我想选择所有这些单元格以更改内部颜色。数组中的单元格表示工作簿中自上一个工作表版本以来发生更改的所有单元格,我需要突出显示它们以查看更改。

我尝试将数组转换为字符串,然后使用以下代码选择它们:

For index = 1 To UBound(RTemp)
    RTempStr = RTempStr & CStr(RTemp(index))
Next

RTempStr = Left(RTempStr, Len(RTempStr) - 1)

Worksheets("R1").Select
Union(RTempStr).Select
Selection.Interior = vbRed

RTemp是我的单元格地址数组

Union 函数返回类型不匹配错误

任何建议如何解决这个问题?或其他选择单元格的方法?

4

2 回答 2

1

只需通过加入创建地址:

Sub jumble()
    Dim ary(1 To 3) As String
    Dim s As String
    Dim r As Range
    ary(1) = "A1"
    ary(2) = "B9"
    ary(3) = "C11"
    s = Join(ary, ",")
    Set r = Range(s)
    r.Select
End Sub
于 2013-10-17T11:40:31.007 回答
1

声明一个范围对象并将非连续范围分配给它。然后,您可以直接更改内部颜色。请参阅此示例。

Sub sample()
    Dim rng As Range

    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A2,C4:C7,D11:D12")

    rng.Interior.ColorIndex = 3
End Sub

我是硬编码"A1:A2,C4:C7,D11:D12"如果您在数组中有单元格地址,那么您可以构造该字符串并将其传递给范围对象。例如

Sub sample()
    Dim Ar(1 To 3) As String
    Dim rng As Range
    Dim strAddress As String
    Dim i As Long

    Ar(1) = "A1:A2"
    Ar(2) = "C4:C7"
    Ar(3) = "D11:D12"

    For i = 1 To 3
        If strAddress = "" Then
            strAddress = Ar(i)
        Else
            strAddress = strAddress & "," & Ar(i)
        End If
    Next

    Set rng = ThisWorkbook.Sheets("Sheet1").Range(strAddress)

    rng.Interior.ColorIndex = 3
End Sub

评论的跟进

如果数组说Cell(4,5)然后使用我在下面创建的函数。

Option Explicit

Sub Sample()
    Dim Ar(1 To 5) As String
    Dim rng As Range
    Dim strAddress As String
    Dim i As Long

    Ar(1) = "Cells(4,5)"
    Ar(2) = "Cells(6,6)"
    Ar(3) = "Cells(7,7)"
    Ar(4) = "Cells(8,12)"
    Ar(5) = "Cells(9,12)"

    strAddress = Join(Ar, "#") '<~~ `Join` Courtsey Gary's Student
    strAddress = GetAddress(strAddress)

    Debug.Print strAddress

    Set rng = ThisWorkbook.Sheets("Sheet1").Range(strAddress)

    rng.Interior.ColorIndex = 3
End Sub

Function GetAddress(sAddr As String) As String
    Dim MyAr
    Dim sTemp As String, sAddrs As Range
    Dim Rw As Long, Col As Long, i As Long

    MyAr = Split(sAddr, "#")

    For i = 0 To UBound(MyAr)
        sTemp = Replace(Replace(MyAr(i), "Cells(", ""), ")", "")
        Rw = Val(Trim(Split(sTemp, ",")(0)))
        Col = Val(Trim(Split(sTemp, ",")(1)))


        If sAddrs Is Nothing Then
            Set sAddrs = ThisWorkbook.Sheets(1).Cells(Rw, Col)
        Else
            Set sAddrs = Union(sAddrs, ThisWorkbook.Sheets(1).Cells(Rw, Col))
        End If
    Next i

    GetAddress = sAddrs.Address
End Function
于 2013-10-17T11:36:54.073 回答