【问题标题】:VBA: How can I make my function work for both vertical and horizontal vectorVBA:如何使我的函数同时适用于垂直和水平矢量
【发布时间】:2015-05-27 12:37:38
【问题描述】:

我有一个向量(行和列),我想为该向量中的每个值计算一个特定的函数(例如 x+5),我想让它显示在指定的单元格数组中。我写了一个函数,在 Excel 中它适用于单个单元格或行向量。但是当我在列向量上尝试它时,它会返回为数组中所有值的第一个单元格计算的值。你能帮我吗,我做错了什么或者为什么它不起作用? 我的代码是这样的

选项基础 1

Public Function TestFunction(arr As Range) As Variant
 Dim i As Integer
 Dim j As Integer
 Dim NoCols As Integer
 Dim NoRws As Integer
 Dim FV() As Double

 NoCols = arr.Columns.Count
 NoRws = arr.Rows.Count


If NoCols = 1 Then
  ReDim FV(NoRws)
     For i = 1 To NoRws
         x = arr.Rows(i)
         FV(i) = x + 5
    Next i

Else
 ReDim FV(NoCols)
    For j = 1 To NoCols
     y = arr.Columns(j)
     FV(j) = y + 5
    Next j

End If

TestFunction = FV()

End Function

【问题讨论】:

  • 你的代码中的FX是什么,你的意思是用FV代替
  • 你 ReDim FX 但声明并返回 FV。我看不出在这两种情况下它会如何工作。此代码是否与您的工作代码完全相同?
  • 是的,我的意思是 FV,只是输入错误。我已经更正了。在我的原始代码中它是相同的并且它不工作
  • 你的假设是错误的。它也适用于列向量。但它在这两种情况下都返回一个行向量。如果给定行向量,是否返回行向量,如果给定列向量,是否返回列向量?

标签: arrays excel vba function vector


【解决方案1】:

我怀疑如果给定行向量,它应该返回一个行向量,如果给定一个列向量,它应该返回一个列向量。如果是的话:

Public Function TestFunction(arr As Range) As Variant
 Dim i As Integer
 Dim j As Integer
 Dim NoCols As Integer
 Dim NoRws As Integer
 Dim FV() As Double

 NoCols = arr.Columns.Count
 NoRws = arr.Rows.Count

 If NoCols = 1 Then
  ReDim FV(1 To NoRws, 1 To 1) ' column vector = multiple rows, 1 column = FV(row, 1), using (1 to ...) DIMs to avoid Option Base 1
  For i = 1 To NoRws
   x = arr.Cells(i, 1)
   FV(i, 1) = x + 5
  Next i
 ElseIf NoRws = 1 Then
  ReDim FV(1 To 1, 1 To NoCols) ' row vector = 1 row, multiple columns = FV(1, column)
  For j = 1 To NoCols
   y = arr.Cells(1, j)
   FV(1, j) = y + 5
  Next j
 End If

 TestFunction = FV()

End Function

【讨论】:

  • 非常感谢,这正是我所需要的。不过我有一个问题......为什么我要避免使用“Option Base 1”?只是代码中少了一行还是会导致任何问题?
  • 这只是我的约定,因为我不能依赖 Option Base。请参阅msdn.microsoft.com/en-us/library/aa266179%28v=vs.60%29.aspx:“Option Base 不会影响 ParamArray(或 Array 函数,当使用其类型库的名称进行限定时,例如 VBA.Array)”。来自模块外部的对象也不会受到影响。所以我认为最好直接声明 LBound 。
【解决方案2】:

不要反对使用二维数组。

这适用于单行或单列或单元格块:

Option Base 1

Public Function TestFunction(arr As Range) As Variant
   Dim i As Long
   Dim j As Long
   Dim NoCols As Long
   Dim NoRws As Long
   Dim FV()

   NoCols = arr.Columns.Count
   NoRws = arr.Rows.Count
   FV = arr

   For i = 1 To NoRws
      For j = 1 To NoCols
         FV(i, j) = FV(i, j) + 5
      Next j
   Next i

   TestFunction = FV()

End Function

【讨论】:

  • 在这种特殊情况下,您的解决方案会更好。但是你也使用二维数组。人们应该知道这些数组是如何工作的。如果它明确地不适用于一块单元格怎么办?和/或如果行向量的函数与列向量的函数不同?
  • @AxelRichter 你是对的............特殊情况需要特殊方法......将 5 添加到任意数组的示例,无论输入是单行还是单列还是简单的单元格块,我的方法都可以使用。 函数单元必须插入到与输入排列同构的排列中。
猜你喜欢
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多