【问题标题】:Excel-VBA: How to get size of selected array in vba code?Excel-VBA:如何在 vba 代码中获取所选数组的大小?
【发布时间】:2012-08-19 16:41:31
【问题描述】:

我正在用 excel 编写一个 vba 函数,它接收一个奇数大小的空方阵并用数字填充它。但是,在调用函数之前,我无法检索它在电子表格中动态选择的数组的大小。我该怎么做?

谢谢!

【问题讨论】:

  • 你能告诉我们dynamically selected in the spreadsheet before the function is called.是什么意思
  • 黑暗中的野刺:x = UBound(MyArray, 2)

标签: excel vba macos


【解决方案1】:

将 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

现在你有两个问题:

  1. 你原来的问题,通过检查 i 和 j 来解决

  2. 一种特殊情况,其中单个单元格范围的值不是数组变量

所以你需要这个:

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

任何其他业务:

有一个无法识别的假设,即:您认为您可以传入当前的 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

认为这就是所有的惊喜。除非您遇到奇特的东西和诸如“这个范围是否计算过?”之类的尴尬问题

【讨论】:

  • 您可能想要处理选择是Range 和多个Areas 的可能性。此方法将仅返回第一个区域的尺寸(这不一定是错误的方法)
猜你喜欢
  • 2015-02-04
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 2017-08-17
  • 2014-04-21
  • 1970-01-01
  • 2016-03-08
  • 2016-05-25
相关资源
最近更新 更多