VBA _ Excel范围注释到数组
我正在处理一个excel文件,其中包含一些单元格注释的下面的值。
下面的VB代码是将值和注释复制到一个数组。
Sub commentToArray() arrayValues = Range("A1:A6").Value arrayComments = Range("A1:A6").Comment.Text End Sub
值数组工作正常,但评论arrays填充错误消息。
你能帮我解决这个问题吗?
谢谢,Aneesh
你的代码有两个错误:
- 您不能使用Comment.Text方法的一个范围的多个单元格。
- 你不能'在不包含注释的单元格上使用Comment.Text 。
这可以为您解决:
Sub commentToArray() Dim arrayValues As Variant Dim ArrayCommnents() As String Dim myRange, commentsRange, mycell As Range Dim i As Integer arrayValues = Range("A1:A6").Value Set myRange = ActiveSheet.Range("A1:A6") Set commentsRange = myRange.Cells.SpecialCells(xlCellTypeComments) arrayLenght = commentsRange.Count ReDim arrayComments(arrayLenght) For Each mycell In commentsRange i = i + 1 arrayComments(i) = mycell.Comment.Text Debug.Print (arrayComments(i)) Next mycell End Sub
说明:
- 我使用范围
myRange
var来评估评论。 接下来,我需要确定哪些单元格包含注释,这是commentsRange
var的目的。 - 我已经使用
.SpcialCells()
方法来只获取带有注释的单元格。 - 然后,我用
.Count
属性得到commentsRange
的长度。 我得到了执行注释的单元格的数量。 - Redimension需要注释的数组。
-
For Each
循环是在包含注释的单元格范围内逐个单元格的注释。 一个增量索引i
来运行数组,你得到它。