我想要一个Access应用程序自动从某个文件夹导入正确的文件。我的想法是获取文件夹中的所有文件,然后从集合中删除错误的文件。最后,我开始导入。
问题是删除部分,VBA不知道在此上下文中的删除方法。
下面是一个示例代码:
Dim objFS As Object
Dim objFolder As Object
Dim objFiles As Object
Dim objF1 As Object
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder(strPath)
Set objFiles = objFolder.Files
' remove files with wrong YearMonth from collection
For Each objF1 In objFiles
If Left(Right(objF1.Name, 8), 6) <> YearMonth Then
' the following line causes the error
objFiles.Remove (objF1.Name)
End If
Next是否没有简单地从objFiles中删除对象的选项?
如果没有,我想我只需要填充另一个数组,存储我想要删除的所有objF1,并将该数组用作实际文件导入的排除筛选器。
编辑:似乎我必须使用数组解决方案。谢谢你的帮助。
edit2:我选择了一个字符串数组,存储我不想导入的所有文件的名称。最终的导入方法检查此列表中的名称。
发布于 2015-03-20 18:44:52
GetFolder方法返回FileCollection的一个实例。根据docs,没有办法从这个集合中删除对象。您可能希望将GetFolder视为一种纯粹的信息性方法。
因此,如果您想坚持删除已处理文件的方法,则必须预先将其复制到可变的VBA.Collection并使用它。
发布于 2015-03-20 19:08:45
如果您处理此集合,则无法修改此集合。你可以创建一个新的列表,在这个列表中你可以添加好的文件。例如:
List<int> listOfNumbers = new List<int>();
for (int i = 0; i < 11; i++)
{
listOfNumbers.Add(i);
}
//The above collection includes 0-10 number but You need only even numbers
//Your current option - not work because You can't modify collection used in foreach
foreach (var item in listOfNumbers)
{
if (item % 2 == 1)
listOfNumbers.Remove(item);
}
//Correct solution
List<int> evenNumbers = new List<int>();
foreach (var item in listOfNumbers)
{
if (item % 2 == 0)
evenNumbers.Add(item);
}发布于 2015-03-20 20:23:19
那ArrayList呢?
Sub SO()
strPath$ = "C:\Users\olearysa\desktop\"
MonthYear$ = "DateFi"
With CreateObject("System.Collections.ArrayList")
fileName = Dir(strPath & "*.*", vbNormal)
While Not fileName = vbNullString
If Len(fileName) > 12 Then
If Mid(fileName, InStrRev(fileName, ".") - 8, 6) = MonthYear Then .Add strPath & fileName
End If
fileName = Dir()
Wend
Debug.Print .count
For i = 0 To .count - 1
'// Example
Workbooks.Open .Item(i)
'// more code here...
Next i
.Clear
End With
End Subhttps://stackoverflow.com/questions/29164516
复制相似问题