我有一组名为apple.xlsx,mango.xlsx等的excel文件。这些文件都在" C:\ Users \ Public \ Fruits \"中。我将所有水果名称存储在fruits.xlsx中。我是Excel-VBA的新手。我可以知道如何将这些文件移动到文件夹Apple,芒果最多500个文件夹,500种不同的水果?
答案 0 :(得分:2)
您可以使用Name Statement更改文件的名称和位置。
例如:
Name "C:\Example_Folder_1\apple.xlsx" As "C:\Example_Folder_2\apple.xlsx"
这会将文件从Example_Folder_2
移至Example_Folder_1
。
如果您已拥有所有文件的名称,则可以将其与循环结合使用。例如,如果水果列表在A2:A500
范围内,则为:
| A
1|Fruits
2|Apple
3|Mango
4|Pear
5|Banana
你可以这样做:
Sub MoveFiles()
Dim flName as String, OldFldr as String, NewFldr as String
Dim Cell as Range
'Set old folder name
OldFldr = "C:\Users\Public\Fruits\"
'Loop through fruits
For each Cell in Thisworkbook.Sheets("Fruits").Range("A2:A500")
'Set new folder name
NewFldr = OldFldr & Cell.Value
'Check whether new fruit specific folder already exists and if not, create it
If Dir(NewFldr , vbDirectory) = "" Then
MkDir (NewFldr & "\")
End If
'Set filename
flName = Cell.Value & ".xlsx"
'Move file to new folder
Name Oldfldr & flName As NewFldr & "\" & flName
Next Cell
End Sub
这会将您的水果特定文件放入特定于水果的文件夹中。