VBA:如何使我的函数适用于垂直和水平向量

时间:2015-05-27 12:37:39

标签: arrays excel vba function vector

我有一个向量(行和列),我想为该向量中的每个值计算一个特定的函数(例如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

2 个答案:

答案 0 :(得分:0)

我怀疑如果给出行向量它将返回行向量而如果给出列向量则返回列向量。如果是,那么:

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

答案 1 :(得分:0)

不要反对使用二维数组。

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

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

enter image description here