VBA数组函数 – 从没有空白的范围返回数组

我在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 

我是VBA的新手,所以这可能是完全错误的。 谢谢!

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

 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 

接下来是If块

 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