2013-01-24 193 views
0

我需要使用VBA將文件從一個文件夾移動到另一個文件夾。將文件從一個文件夾移動到另一個文件夾

For m = 1 To fnum 
    MsgBox " Please Select " & m & "files" 
    ffiles(m) = Application.GetOpenFilename 
Next m 

If Dir(outputfolder) = "" Then 
    fso.createfolder (outputfolder) 
End If 

fso.Movefile ffiles(m), outputfolder " getting error at this place " 

我收到一條錯誤消息。

Error message id "Runtime error 438 . Object doesnt support this property " 
+3

並且該錯誤消息是...? – LittleBobbyTables

+0

錯誤消息ID「運行時錯誤438。對象不支持此屬性」 – newjenn

+0

對於初學者,我沒有在代碼中的任何地方看到'fso'聲明。其次,爲什麼要創建一個'ffiles'數組,然後只移動最後一個文件? – LittleBobbyTables

回答

1

我最喜歡的做法。使用SHFileOperation API

Option Explicit 

Private Declare Function SHFileOperation Lib "shell32.dll" _ 
Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long 

Private Const FO_MOVE As Long = &H1 
Private Const FOF_SIMPLEPROGRESS As Long = &H100 

Private Type SHFILEOPSTRUCT 
    hWnd As Long 
    wFunc As Long 
    pFrom As String 
    pTo As String 
    fFlags As Integer 
    fAnyOperationsAborted As Long 
    hNameMappings As Long 
    lpszProgressTitle As Long 
End Type 

Sub Sample() 
    Dim fileToOpen As Variant 
    Dim outputfolder As String 
    Dim i As Long 

    outputfolder = "C:\Temp\" 

    fileToOpen = Application.GetOpenFilename(MultiSelect:=True) 

    If IsArray(fileToOpen) Then 
     If Dir(outputfolder) = "" Then MkDir outputfolder 

     For i = LBound(fileToOpen) To UBound(fileToOpen) 
      Call VBCopyFolder(fileToOpen(i), outputfolder) 
     Next i 
    Else 
      MsgBox "No files were selected." 
    End If 
End Sub 

Private Sub VBCopyFolder(ByRef strSource, ByRef strTarget As String) 
    Dim op As SHFILEOPSTRUCT 
    With op 
     .wFunc = FO_MOVE 
     .pTo = strTarget 
     .pFrom = strSource 
     .fFlags = FOF_SIMPLEPROGRESS 
    End With 
    '~~> Perform operation 
    SHFileOperation op 
End Sub 
+0

非常感謝@sidhhart潰敗 – newjenn

相關問題