如何使不连续的单元格范围适用于每个引用的单元格

How to make an noncontiguous range of cells work for every cell referenced

我有一个不连续的范围,我希望用户在该范围内的每个单元格中写入的任何内容都显示在我制作的 table 的列中。在我的 table 的第一列中,当用户在一个指定的单元格中添加一个值一直到 18 时,我在 table 中有每个生成的条目的程序编号。我重命名了每个范围内的单元格为 "Space_ (some number)"。即使我已经在三个指定的单元格中写入,我的 table 只显示第一个指定单元格中的第一个值。

到目前为止,这是我的代码:

Sub test2()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
Dim i As Integer
Dim rng As Range

Set rng = ws.Range("Space_7, Space_10, Space_13, Space_16, Space_19, Space_22, Space_25, Space_28, Space_31, Space_34, Space_37, Space_40, Space_53, Space_56, Space_59, Space_62, Space_65, Space_68")


ws.Range("A13:A31,B13:B31").ClearContents

For i = 1 To 18

If Not IsEmpty("rng") Then
ws.Range("A12").Offset(1).Value = i
End If
Exit For
Next i

If Not IsEmpty("rng") Then
    ws.Range("B12").Offset(1).Value = rng.Value
End If

End Sub

这应该可以解决我在评论中提到的各种问题:

Sub test2()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
Dim i As Long
Dim rng As Range, r As Range

With ws
    Set rng = .Range("Space_7, Space_10, Space_13, Space_16, Space_19, Space_22, Space_25, Space_28, Space_31, Space_34, Space_37, Space_40, Space_53, Space_56, Space_59, Space_62, Space_65, Space_68")
    .Range("A13:B31").ClearContents
    For Each r In rng.Areas
        If Not IsEmpty(r) Then
            .Range("A13").Offset(i).Value = i + 1
            .Range("B13").Offset(i).Value = r.Value
            i = i + 1
        End If
    Next r
End With

End Sub

这里有几件事 - 与其尝试将所有命名范围放入 Range,不如将它们单独放入 Array 并循环遍历它们 - 如果它们不是空白,请放入单元格中的值。

您的 .Offset 总是在第 12 行下方显示 1,因此您只能看到一行数据。

Sub test2()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
Dim i As Long, j As Long
Dim rngarray As Variant

rngarray = Array("Space_7", "Space_10", "Space_13", "Space_16", "Space_19", "Space_22", "Space_25", "Space_28", "Space_31", "Space_34", "Space_37", "Space_40", "Space_53", "Space_56", "Space_59", "Space_62", "Space_65", "Space_68")
j = 12

ws.Range("A13:B31").ClearContents

For i = 0 To UBound(rngarray)

    If ws.Range(rngarray(i)).Value <> "" Then
        ws.Range("A12").Offset(j - 11).Value = i + 1
        ws.Range("B12").Offset(j - 11).Value = ws.Range(rngarray(i)).Value
        j = j + 1
    End If

Next i

End Sub

我会按如下方式进行:

Sub test2()

    Dim i As Integer
    Dim rng As Range, cell As Range

    With ThisWorkbook.Sheets("Sheet1")
        .Range("A13:A31,B13:B31").ClearContents

        Set rng = .Range("Space_7, Space_10, Space_13, Space_16, Space_19, Space_22, Space_25, Space_28, Space_31, Space_34, Space_37, Space_40, Space_53, Space_56, Space_59, Space_62, Space_65, Space_68")

        For Each cell In rng.SpecialCells(xlCellTypeConstants).Areas
            ws.Range("A12:B12").Offset(i).Value = Array(i + 1, cell(1, 1).Value)
            i = i + 1
        Next
    End With    
End Sub