0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[VBA/VBS]Scripting.FilesystemObjectのGetparentfoldernameの空白を回避するUDF関数 fnParentfolder

Posted at

Filesystemobjectに"C:"のようなRootフォルダが入ったときParentfoldernameは空白になり、エラーが起きます。
これを回避すべくFolderでもFileでもParentFolderが空白な時はドライブレターを取得してRootFolderを返します
欠点は実在するFolder、Fileにしか確実に効かない点です。これはFileかFolderかの判定にFolderExistsを用いているためです。今回の関数はこの欠点も改善し、実在しているドライブのルートフォルダの実在しないファイルや、実在しないドライブのルートに直下のファイルやフォルダでもなるべく返します。
サーバーの場合はドライブが割り当てられていれば確実に動きますが、\\Server\rootのような場合の挙動は資料が有りません。

いままでなぜIsRootやGetDriveがあるのか不思議だったのですが、おそらくこういう使い方を想定しているのでしょう。
またFolderExistsはFalseでも実在するファイルやフォルダではありません。ここにもポイントがあります。
実在しなくてもParentfolderNameは確実に動くためです。
FileSystemObject:フルパスからファイル名、パスを取得する(GetFileName、GetParentFolderName)

object ・・・ FileSystemObject オブジェクトを指定します。
path ・・・ 対象となるパスを指定します。<<つまり、ファイルではない
戻り値 ・・・ 引数 path で指定したパスにある最後のコンポーネント(「フォルダ名」または「ファイル名」)の親フォルダ名を含む文字列。

引数 path で指定されたコンポーネントの親フォルダがない場合は、長さ 0 の文字列 (“”) を返します。<今回の関数が必要になった原因
GetParentFolderName メソッド は、引数 path で指定したパスが存在するかどうかは確認しません。<<つまり、文字列をそうさする形でひとつ上のフォルダを返していることになる。VBAでもフォルダ名をSplitで分割して配列にいれて取得する方法があるが、それも実在しないファイルやフォルダでもよい。

VBA,VBS
Function fnParentFolder(strFolder)
Dim fnFso
Set fnFso = CreateObject("Scripting.FileSystemObject")
IF fnFso.folderExists(strFolder) Then
  If fnFso.getParentfoldername(strFolder)="" Then
    IF fnFso.getFolder(strFolder).isrootfolder Then
    fnParentFolder = fnFso.getDrive(fnFso.getfolder(strFolder)) & "\"
    Exit Function
    End If
  Else
  fnParenFolder =  fnFso.getParentfoldername(strFolder)
  Exit Function
  End If
Else
  On Error Resume Next
  If  fnFso.getParentfoldername(strFolder) = "" Then '実在しないフォルダならここで空白になる
    If err.Number <> 0 Then Wscript.Echo Err.Number , Err.Description :Err.clear
    fnParentFolder = strFolder 'そのまま返す
    Exit Function
  Else
    fnParentFolder = fnFso.GetParentfoldername(strFolder)
    Exit Function
  End iF
End if
Set fnFso = Nothing
On Error Goto 0
End Function
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?