2016-05-03 6 views
1

開いているときのファイルパスを比較したいと思います。ファイルを開いたときのパスを比較するVBAコード

パスを開くと、パスが "\ server \ myfolder1 \ myfolder2 \"であるかどうかを比較します。 TRUEの場合は何もしないでください。 FALSEの場合は、MSGBOXを表示してファイルを閉じます。

私は、TE次のコードをしようと試みた:私は私のローカルディスクにコピーを作成するときには機能し

Private Sub Workbook_Open() 

Dim LocalFile As String 
LocalFile = "\\Server\folder1\folder2" 

If ActiveWorkbook.Path <> LocalFile Then 
MsgBox ("This file is not original") 

End If 

Range("B2").Value = ActiveWorkbook.Path 

End Sub 

を。しかし、私がショートカットやネットワークパスを指すマッピングから開くと、動作しません。

ヒント?

答えて

0

は、完全なネットワークパスにドライブ文字を変換しよう

Private Sub Workbook_Open() 
    ChDir ("\\172.16.5.4\BTS-Team") 
    If ActiveWorkbook.Path <> CurDir Then 
     MsgBox ("This file is not original") 
    End If 
    Range("B2").Value = ActiveWorkbook.Path 
End Sub 
+0

に変換する機能コードです。 CurDirは常に同じなので、ChDirはテストを廃止しませんか?私がそれを正しく理解していないなら、これを私に説明してください。どうもありがとうございました。 –

+0

あなたは上記のコードを試しましたか? chdirはディレクトリを変更するだけですcurdirは現在のディレクトリです –

+0

ええ、まあまあ、あなたを攻撃したくない、ごめんなさい、私は理解したい、ディレクトリを特定のフォルダに変更し、アクティブなworkbook.pathがそのフォルダ? ActiveWorkbook.Path <> "\\ 172.16.5.4 \ BTS-Team"が同じ –

1

の下にこれを試してみてください。マイクロソフトの参照コードhere

は、ここでそのショートカットを介してファイルを開くことを防止する方法完全なネットワークパス

Option Explicit 

Declare Function WNetGetConnection32 Lib "MPR.DLL" Alias _ 
    "WNetGetConnectionA" (ByVal lpszLocalName As String, ByVal _ 
    lpszRemoteName As String, lSize As Long) As Long 

Sub Test() 
    If Not IsError(GetNetPath("Z")) Then 
     MsgBox GetNetPath("Z") 
    Else 
     MsgBox "Error" 
    End If 
End Sub 

Function GetNetPath(ByVal DriveLetter As String) 
    Dim lpszRemoteName As String * 255 
    Dim cch As Long 
    Dim lStatus As Long 

    DriveLetter = DriveLetter & ":" 
    cch = 255 
    lStatus = WNetGetConnection32(DriveLetter, lpszRemoteName, cch) 

    If lStatus& = 0 Then 
     GetNetPath = application.clean(lpszRemoteName) 
    Else 
     GetNetPath = CVErr(xlErrNA) 
    End If 
End Function 

Private Sub Workbook_Open() 

    Dim LocalFile As String 
    Dim CurrentPath As String 
    Dim CurrentDrive As String * 1 
    Dim CurrentDriveMap As Variant 

    LocalFile = "\\Server\folder1\folder2" 
    CurrentPath = ThisWorkbook.Path 
    CurrentDrive = CurrentPath 
    CurrentDriveMap = GetNetPath(CurrentDrive) 
    If Not IsError(CurrentDriveMap) Then 
     CurrentPath = CurrentDriveMap & Mid(CurrentPath, 3, Len(CurrentPath))    
    End If 
    If CurrentPath <> LocalFile Then 
     GoTo NotOriginalHandler 
    End If 
    Range("B2").Value = ActiveWorkbook.Path 
    Exit Sub 

NotOriginalHandler: 
    MsgBox ("This file is not original") 
    ThisWorkbook.Close 
End Sub 
+0

どのようにショートカットでファイルを開くのを防ぐ必要がありますか?私はあなたに非常に感謝を説明していただければ幸いです。 –

+0

ドライブを完全なマッピングパスに変換できるのであれば、明らかに 'LocalFile'文字列と比較することができます – Rosetta

+0

私はこれが彼の問題ではないと思います。ショートカットは、これを解決しない同じパスを持つ全く同じファイルへのポインタ以外は何もありませんか?とにかく本当にきれいでいいコードのようです;) –

関連する問題