ファイルを移動する : Excel

Excel VBAでファイルを移動するには、Nameステートメントを使用します。
Nameステートメントは、ファイル名の変更もできます。

構文 : Name oldpathname As newpathname

引数
oldpathname : 移動するファイル名を指定します。
newpathname : 移動先の新しいファイル名を指定します。既に存在しているファイル名は指定できません。


Homeに戻る > Excel ファイル操作のTipsへ


Excel実行画面

「移動元ファイル」と「移動先フォルダ」を指定し、「移動開始」ボタンをクリックすると、指定フォルダに移動します。
ファイル移動ソフト


Excel VBA実行コード

Option Explicit

'ファイル選択ダイアログ
Public Function SelectFile_single()
    Dim sfile As String
    Dim i As Integer
    Dim s As String

    sfile = Application.GetOpenFilename("ファイルを選択してください (*.xls), *.xls")
    If sfile = "False" Then
        SelectFile_single = ""
    Else
        SelectFile_single = sfile
    End If
End Function

'フォルダ選択ダイアログ
Public Function SelectFolder_FileDialog()
    If Application.FileDialog(msoFileDialogFolderPicker).Show Then
        SelectFolder_FileDialog = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
    Else
        SelectFolder_FileDialog = ""
    End If
End Function

'フルパスからファイル名のみ取得
Function GetFileName(fullpath As String) As String
    Dim i As Integer
    Dim nlen As Integer
    Dim s As String

On Error GoTo Errsub
    nlen = Len(fullpath)
    For i = nlen To 0 Step -1
        s = Mid$(fullpath, i, 1)
        If s = "\" Then Exit For
    Next
    s = Right$(fullpath, nlen - i)
    GetFileName = s
    Exit Function
Errsub:
    GetFileName = ""
End Function

Private Sub CommandButton1_Click()
    Range("E4") = SelectFile_single
End Sub

Private Sub CommandButton2_Click()
    Range("E8") = SelectFolder_FileDialog
End Sub

Private Sub CommandButton3_Click()
    Dim fname As String
    Dim sdir As String
       
    If Range("E4") = "" Then
        MsgBox "移動元ファイルを選択してください。"
        Exit Sub
    End If
    
    If Range("E8") = "" Then
        MsgBox "移動先フォルダを選択してください。"
        Exit Sub
    End If
        
    'パス名からファイル名のみ取り出し
    fname = GetFileName(Range("E4"))
    
    If Right(Range("E8"), 1) <> "\" Then
        sdir = Range("E8") & "\"
    Else
        sdir = Range("E8")
    End If
    
    'ファイルの移動
    Name Range("E4") As sdir & fname
    MsgBox "ファイルを移動しました。"
End Sub



Homeに戻る > Excel ファイル操作のTipsへ

■■■
このサイトの内容を利用して発生した、いかなる問題にも一切責任は負いませんのでご了承下さい
■■■
当ホームページに掲載されているあらゆる内容の無許可転載・転用を禁止します


Copyright (c) Excel-Excel ! All rights reserved