【发布时间】:2019-07-28 13:48:12
【问题描述】:
首先:我是 VBA 的新手,所以如果这个问题很琐碎,请原谅,但是这个错误让我整天忙于 - 我完全不知道。
我正在开发一个小宏来查看文件夹、计算文件数并用完整的文件名和名称的特定部分填充二维数组。所以我在我的主子中创建一个数组并调用将空数组作为参数并填充它的函数。
我的宏看起来有点像这样:
Private Sub whatever()
Dim arr(10, 2) As String
Dim count As Integer
CheckFolder(arr, "somepath", count)
End Sub
Sub CheckFolder(ByRef arr() As String, strPath As String, count As Integer)
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Dim fileCount As Integer
Dim temp(10, 2) As String
fileCount = 1
WriteToLog "zähle Files in Ordner " & strPath & "... "
Dim path As String
path = ActiveWorkbook.path & "\" & strPath
Set queue = New Collection
queue.Add fso.GetFolder(path) '- Pfad zum Ordner
Do While queue.count > 0
Set oFolder = queue(1)
FolderName = fso.GetFileName(oFolder)
queue.Remove 1 'dequeue
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
Filename = fso.GetFileName(oFile)
'- my guess is the next two line are the problem?
temp(fileCount, 1) = Filename
temp(fileCount, 2) = StringCutter(Filename)
fileCount = fileCount + 1
Next oFile
Loop
arr = temp
count = fileCount
End Sub
我不确定,但我认为这两行是问题所在(因为之前的其他逻辑运行得非常好)
temp(fileCount, 1) = Filename
temp(fileCount, 2) = StringCutter(Filename)
此处调用的函数“StringCutter”返回文件名的子字符串。我之前测试过该功能并且我可以工作,所以我认为它不会引起任何问题。
如果有人能告诉我我的错误在哪里,我将不胜感激。
编辑: 这是 StringCutter 函数,它接受一个字符串并剪切它的某个部分并返回该部分。如前所述,当我在填充数组之外使用此函数时,它可以正常工作。
Function StringCutter(str As String) As String
Dim ret As String
Dim retLen As Integer
Dim pos As Integer
retLen = Len(str)
ret = Right(str, (retLen - 31))
pos = InStr(ret, "_")
If (pos > 0) Then
ret = Left(ret, (pos - 1))
Else
ret = Left(ret, 4)
End If
StringCutter = ret
End Function
希望对你有帮助
【问题讨论】:
-
你得到什么错误,在哪一行?
filecount出错时的值是多少? -
你也可以发布你的
StringCutter函数吗? -
运行代码时究竟会发生什么?
-
@SJR:我收到错误 13:“类型不匹配”。当我尝试执行“arr = temp”时,我的宏跳转到错误例程。
-
@AlexdeJong:我编辑了我的帖子并添加了功能。希望有帮助
标签: arrays excel vba string byref