Yas*_*han 3 excel vba excel-vba excel-vba-mac
我正在excel中编写一个vba函数,它接收一个奇数大小的空方阵并用数字填充它.但是,在调用函数之前,我无法检索它在电子表格中动态选择的数组的大小.我该怎么做?
谢谢!
将Range对象传递给函数并查看值:
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
Run Code Online (Sandbox Code Playgroud)
现在你有两个问题:
你原来的问题,通过检查i和j来解决
一种特殊情况,其中单细胞范围的值不是数组变体
所以你需要这个:
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
Run Code Online (Sandbox Code Playgroud)
其他业务:
有一个未被认识的假设,即:您认为可以传入当前的Application.Selection,它将始终是一个范围.它也可以是控件,图表或图表系列......
......不,你不能依赖于这会引起类型不匹配的运行时错误.是的,你已经调用了Option Explicit,是的,你打字了SourceRange as Excel.Range,你的母亲,你的教区牧师和一位和平大法官看着你这样做; 在午夜之后尝试在一块看起来阴险的岩石上牺牲一些东西,也许 VBA运行时会相信你.
所以你还需要这个:
If Not TypeOf SourceRange Is Excel.Range Then
' Raise an error or Exit Sub
End If
Run Code Online (Sandbox Code Playgroud)
我认为这都是惊喜.除非你遇到异国情调和尴尬的问题,比如"这个范围是否计算好了?"