【问题标题】:Get a range of cells with all cell attributes获取具有所有单元格属性的单元格范围
【发布时间】:2015-08-14 21:16:38
【问题描述】:

是否可以一次性获取具有所有单元格“属性”的单元格范围,例如值、单元格背景颜色、单元格字体等,然后将其存储在数组中。

而不是多次迭代范围并一次获取每个单独的属性?

例如,这将是意图,虽然我知道它不起作用:

Dim cellData() As Variant
cellData= Range("A36:W36")
Debug.Print cellData(1,1).Value
Debug.Print cellData(1,1).Interior.ColorIndex

谢谢

【问题讨论】:

  • 我不认为你可以。如果您在存储每个单元格的当前颜色状态之后,我建议将行/范围复制到另一张表。
  • @DaveMac - 应该可以,只需创建一个多维数组并使用不同的维度来存储单元格信息的一部分。 (现在正在做某事)。
  • 不确定是否不遍历范围,我尝试过 arr = Range("B2:B5").Cells.Interior.ColorIndex 其中 arr 是一个变体。
  • 最终目标是什么?所有的值都包含在范围对象中——你可以直接从那里访问它们,那么一旦你有了这个数组,你到底想做什么呢?

标签: excel vba


【解决方案1】:

这是我做的有点快,看看它是否在正确的道路上:

Sub addToArray()
Dim rng As Range, cel As Range
Dim cellAttributes()
Dim i As Integer, k As Integer

' We're going to store 2 cells' attributes.  We're going to use 3 attributes, hence the next line
ReDim cellAttributes(1 To 2, 1 To 3) ' since you want Value, Font, and Color, I chose up to three. Change this if you want more attributes
'The array will be cellAttributes([Cell Address],{value, font, color})

Set rng = Range("A1:A2")
i = 1
k = 1
For Each cel In rng
    cellAttributes(i, k) = cel.Value
    cellAttributes(i, k + 1) = cel.Font.Name
    cellAttributes(i, k + 2) = cel.Interior.ColorIndex
    Debug.Print "Cell " & cel.Address & " has a value of: " & cellAttributes(i, 1) & ", font: " & cellAttributes(i, 2) & " and bg color index: " & cellAttributes(i, 3)
    i = i + 1
    k = 1
Next cel


End Sub

在仔细阅读您的问题后,您到底想做什么?上面的宏将一次查看每个单元格,然后将属性应用于数组,然后再继续。当然,您可以使这更加动态(我使用的“幻数”比我习惯的要多,但我只是想确保这是(或不是)您正在寻找的东西)。

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多