【问题标题】:CSE UDF VBA Returning only first elementCSE UDF VBA 仅返回第一个元素
【发布时间】:2020-03-20 09:20:40
【问题描述】:

我正在尝试编写一个返回数组(CSE 函数)的 UDF。 特别是,UDF 接收文件夹路径并列出其中的所有内容。

我想我快到了,因为在调试函数时确实将其所有数组元素分配给了我想要的值,但是当在 Excel 上的选定范围内执行 Ctrl + Shift + Enter 时,它只显示第一个元素。

Function VBA_ListFilesIn(mypath As String) As Variant
Dim myArray() As String
Dim myArraySize As Integer

Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer

myArraySize = CountFilesInFolder(mypath)
ReDim myArray(1 To myArraySize)

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(mypath)

i = 1
For Each oFile In oFolder.Files
myArray(i) = oFile.Name
If i < myArraySize Then
i = i + 1
End If
Next oFile
VBA_ListFilesIn = myArray

End Function

这是结束函数之前我当地人的片段......

CountFilesInFolder 是这样的: https://wellsr.com/vba/2016/excel/vba-count-files-in-folder/

我四处寻找这个问题,但我只能找到有#VALUE的人,基本上连这最后一步都达不到。

注意:将函数的返回类型从 variant 更改为 string() 会导致同样的问题。

它可能有一个非常明显的解决方案,但我在这里迷失了一段时间。

【问题讨论】:

  • 您的数组是一维的(1 to 6),但范围始终是二维的(rows, columns),即使它只有一行或一列,也有 2 个维度,如 (1 to 6, 1 to 1) 表示 6 行 1 列。这可能是您遇到的问题。
  • 谢谢...我知道这并不难...我只是想出来!
  • 用一个例子把它写成答案。

标签: excel vba


【解决方案1】:

您的数组是一维的(1 to 6),但范围始终是二维的(rows, columns),即使它只是一行或一列,也有 2 个维度,例如 (1 to 6, 1 to 1) 表示 6 行 1 列。这可能是您遇到的问题。

例子:

Option Explicit

Public Function Return1Dimension() As String()
    Dim arr(1 To 3) As String

    arr(1) = "First"
    arr(2) = "Second"
    arr(3) = "Third"

    Return1Dimension = arr
End Function



Public Function Return2Dimensions() As String()
    Dim arr(1 To 3, 1 To 1) As String

    arr(1, 1) = "First"
    arr(2, 1) = "Second"
    arr(3, 1) = "Third"

    Return2Dimensions = arr
End Function

【讨论】:

  • 这个问题的答案很好,但请注意,您可以从 VBA --> 使用一维数组的工作表中编写一行。例如[c1:l1] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0) 有效。反之不是正确的,因为v = [c1:l1] 将产生一个二维数组。
  • @RonRosenfeld 是的,你是对的!我认为连续的文件列表没有多大意义。除了你所说的,如果你转置它,你还可以将一维数组写入一列:Range("A1:A10").Value = Application.WorksheetFunction.Transpose(Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0))
  • 是的,转置一维数组会创建一个二维数组。
  • 谢谢,明白了!出于我的目的,我最终只使用了 =TRANSPOSE(....) 但今天学到了一些东西。
猜你喜欢
  • 2017-03-29
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2011-05-09
相关资源
最近更新 更多