Excel VBA:如何在VBA代码中获取选定数组的大小?
我正在excel中编写一个vba函数,它接受一个奇数大小的空方阵,并用数字填充它。但是,在调用函数之前,我无法检索它在电子表格中动态选择的数组的大小。我该怎么做Excel VBA:如何在VBA代码中获取选定数组的大小?,excel,vba,macos,Excel,Vba,Macos,我正在excel中编写一个vba函数,它接受一个奇数大小的空方阵,并用数字填充它。但是,在调用函数之前,我无法检索它在电子表格中动态选择的数组的大小。我该怎么做 谢谢 将范围对象传递到函数中并查看值: Public Function WhatIsTheMatrix(SourceRange as Excel.Range) As Variant Dim arrSource as Variant Dim arrOutPut as Variant Dim i As Long, j
谢谢 将范围对象传递到函数中并查看值:
Public Function WhatIsTheMatrix(SourceRange as Excel.Range) As Variant
Dim arrSource as Variant
Dim arrOutPut as Variant
Dim i As Long, j As Long
arrSource = SourceRange.Value2
i = Ubound(arrSource, 1)
j = Ubound(arrSource, 2)
' The lower bounds of an array obtained from a range are always 1
' code
' more code
' even more code
WhatIsTheMatrix = arrOutPut
End Function
现在有两个问题:
If SourceRange.Cells.Count = 1 Then
Redim arrSource(1 to 1, 1 To 1)
arrSource(1,1) = SourceRange.Value2
Else
arrSource = SourceRange.Value2
End If
If Not TypeOf SourceRange Is Excel.Range Then
' Raise an error or Exit Sub
End If
任何其他业务:
有一个未被认可的假设,即:您认为您可以通过当前应用程序。选择,它将始终是一个范围。它也可以是控件、图表或图表系列
…不,您不能依赖此操作来引发类型不匹配的运行时错误。是的,您调用了显式选项,是的,您以Excel.Range键入了SourceRange,您的母亲、教区牧师和治安法官看着您这样做;试着在午夜后在一块看起来邪恶的岩石上牺牲一些东西,也许VBA运行时会相信你
所以你也需要这个:
If SourceRange.Cells.Count = 1 Then
Redim arrSource(1 to 1, 1 To 1)
arrSource(1,1) = SourceRange.Value2
Else
arrSource = SourceRange.Value2
End If
If Not TypeOf SourceRange Is Excel.Range Then
' Raise an error or Exit Sub
End If
我想这就是所有的惊喜。除非你对异国情调和尴尬的问题感兴趣,比如“这个范围是计算出来的吗?”你能告诉我们在调用函数之前,在电子表格中动态选择是什么意思吗
您可能需要处理选择范围为多个区域的可能性。此方法将仅返回第一个区域的尺寸(这不一定是错误的方法)