Skip to content

Instantly share code, notes, and snippets.

@HaruhiroTakahashi
Created July 1, 2016 04:11
Show Gist options
  • Save HaruhiroTakahashi/fbc8cd74b13d5e7ff00f174424a8c4d4 to your computer and use it in GitHub Desktop.
Save HaruhiroTakahashi/fbc8cd74b13d5e7ff00f174424a8c4d4 to your computer and use it in GitHub Desktop.
パスを分解するインスタンスメソッド
Option Explicit
Option Base 1 '配列最初の要素番号を1に設定する
'【パス構成要素抽出メソッド】
'「このインスタンスメソッドの使い方」
'宣言方法 → Set hoge = New PathSeparation_Cls
' huga = hoge.elemPath(フルパス)
' huga(m, n)→引数m,nの値によってファイル名およびパスの取得ができる。
'
'「C:\Folder\Book.xlsx」を例にした概要
'・m → 必ず1か2を指定する。返り値は以下のように設定してある。
' [1.n] → n番目要素名
' [2.n] → n番目要素名のパス
'・n → 必ず1以上の値を指定する。フルパス一番右の要素を1番目とし、ドライブ手前までをn番目として要素を指定する。
' 1番目 Book.xlsx = [1.1]
' 2番目 Folder = [1.2]
Dim n As Long, elemMax As Long
Dim childe As String, pathToChilde As String
Dim parent As String, pathToParent As String
Function elemPath(getPath As String) As Variant
Dim result() As Variant
Const argMax As Long = 2 '配列 m の最大要素番号を2に指定
elemMax = Len(getPath) - Len(Replace(getPath, "\", ""))
ReDim result(argMax, elemMax)
For n = 1 To elemMax
Call elemAllocation(getPath)
result(1, n) = childe '要素名取得
result(2, n) = pathToChilde 'パス取得
Next n
elemPath = result
End Function
Private Sub elemAllocation(getPath)
If n = 1 Then
pathToChilde = getPath
childe = Dir(getPath)
Else
pathToChilde = pathToParent
childe = Dir(pathToChilde, vbDirectory)
End If
pathToParent = Replace(pathToChilde, "\" & childe, "")
If n = elemMax Then 'nが最大要素の時ドライブ名を取得する
parent = Left(CurDir, 1)
Else
parent = Dir(pathToParent, vbDirectory)
End If
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment