VBA数组函数 - 无空白范围返回数组

问题描述:

我正在努力解决VBA中的一个基本问题,并希望得到一些帮助。我想定义一个函数返回从一系列数组没有空格,如下图所示:VBA数组函数 - 无空白范围返回数组

enter image description here

所以,当我打电话的欧式期权细胞的功能,函数应该返回数组没有任何空白,就像在右边一样。

这是我到目前为止的代码:我是一个新手,以VBA

Function portfolioX(N) 
    Dim MyArray(3) 
    Dim i As Integer 
    counter = 1 
    For i = 1 To N 
     If IsEmpty(i) Then 
      Next i 
     Else 
      portfolio = MyArray 
      MyArray (counter) 
      counter = counter + 1 
      Next i 
     End If 
End Function 

,所以这可能是完全错误的。谢谢!

+0

首先要学习的时候学习VBA是子程序和函数的区别。当你想要简单地向单个单元格添加适当的值时,请使用函数。当你想做任何其他形式的数据表操作时,你需要使用一个子程序。因此,我不确定你希望代码能为你做什么。如果你能澄清一点,我会很乐意提供帮助 – RGA

+0

你目前还不清楚你在做什么。你能详细解释一下吗?请包括应评估哪些数据,您希望评估的方式以及预期结果。 – Vegard

+0

嗨@RGA谢谢你的帮助!如上图所示,我需要一个以范围作为输入的函数(例如A1:A13)。该函数应该输出一个数组(A18:A21以上)和范围的内容,从而不应考虑空白。因此,如果在图片范围内调用该功能(以绿色显示),则输出应该是右侧的单元格(图中以白色显示)。更清楚了吗? –

如果语句和循环是代码块。你不能交错代码块。

Function portfolioX(N) 

    For i = 1 To N ' Block 1 starts 
     If IsEmpty(i) Then ' Block 2 starts 
     Next i 'Block 1 can't loop back because Block 2 has't closed 
    Else 
     portfolio = MyArray 
     MyArray (counter) 
     counter = counter + 1 
    Next i 'Block 1 can't loop back because Block 2 has't closed 
    End If ' Block 2 

End Function 

当编码它是代码实践写那么完整环结构中的内码继续进行。 我会写For循环第一

For i = 1 to N 

next i 

接下来是如果块

For i = 1 To N 
    If IsEmpty(i) Then 

    End If 
Next i 

最后

Function portfolioX(N) 
    Dim MyArray(3) 
    Dim i As Integer 
    counter = 1 
    For i = 1 To N ' Block 1 Starts 
     If IsEmpty(i) Then Block 2 Starts 
      portfolio = MyArray 
      MyArray (counter) 
      counter = counter + 1 
     End If ' Block 2 Closes 
    Next i 'If the Loop Condition is meet, Block 1 Closes, else i is incremented and the loop starts over 
End Function 

鉴于你问了,我写了一个快速分这将采取您突出显示的范围,并将这些值粘贴到行尾的空白单元格中。希望这能给你一个你希望完成的事情的开始。

Sub RemoveBlanks() 

Dim OriginalRange As Range, WorkCell As Range, PasteCol As Integer 
Set OriginalRange = Selection.Rows(1) 'Ensures only one row of data is selected 
PasteCol = Range(Cells(OriginalRange.Row, ActiveSheet.UsedRange.Columns.Count + 2).Address).End(xlToLeft) 
For Each WorkCell In OriginalRange 
    If Not IsEmpty(WorkCell) Then 
     Cells(OriginalRange.Row, PasteCol).Value = WorkCell.Value 
     PasteCol = PasteCol + 1 
Next WorkCell 

End Sub 

根据您的问题,并在该线程的意见,我知道你希望采取一个给定的范围(供给过程),打印所有非空值在一定范围内开始在列同一行R(第18栏)。

在评论中,您提供范围A1:A13A18:A21,但这些与您的屏幕截图不匹配。我假设你的意思是第1行(或任意行),列1〜13,列18至21

下面是该问题的解决方案:

Sub arrayPaster(rng As Range) 
    Dim s() As Variant, r() As Variant, j As Integer 

    ReDim r(1 To 1, 1 To 1) 
    s = rng.Value 
    j = 1 

    For i = 1 To UBound(s, 2) 
     If s(1, i) <> "" Then 
      ReDim Preserve r(1 To 1, 1 To j) 
      r(1, j) = s(1, i) 
      j = j + 1 
     End If 
    Next i 

    Range("R" & rng.Row).Resize(1, UBound(r, 2)).Value = r 
End Sub