LoginSignup
0
0

More than 1 year has passed since last update.

ファイル名の括弧内の文字を抜き出す VBA マクロ

Last updated at Posted at 2021-12-29

はじめに

提出ファイルの集約といったタスクで、誰が提出したか把握するため、ファイル名に各自のID、あるいは名前等を入れるような命名規則にしたことはありますか?自分の仕事はそんなのばかりです。そんな地道な仕事をエクセルにお手伝いしてもらうため、ファイル名から名前を抜き出す関数を作ってみました。

使用例

例えば【】に自分の名前を入力して提出しなさい、というルールで進めた場合下記のようなファイルが来ると思うのですが、ここから下記のような抜き方ができるといいな、という関数です。

-【山田太郎】提出ファイル.xlsx → 山田太郎 だけ抜き出す
-【Yamada Taro】提出ファイル.xlsx → Yamada Taro を抜く

またカッコには半角のカッコ記号の他、上記のような【「[等々...結構種類があり、記号が変更になるたびにプログラムを書き換えるのはスマートではありません。

ソースコード

getBraceInside という名前で作っています。列挙型で括弧の形を定義しており、指定する括弧を変更すれば別の形でもプログラムの変更なしで対応できます。

Option Explicit

Private Const mtContextID As Integer = 10

Public Enum BracketType
    parenthesis = 1      ' () parentheses ASCII
    brace = 2            ' {} braces, Curly brackets
    bracket = 3          ' [] square brackets
    quote = 4            ' '' single quotes
    jp_brace = 5         ' 「」鍵括弧
    jp_bracket = 6       ' 【】
    wide_parenthesis = 7 ' () full-width parenthesis
    wide_brace = 8       ' {} full-width braces, curly brackets
    wide_bracket = 9     ' [] full-width square brackets
    jp_double_bracket = 10 ' 『』 Japanese double hook brackets
End Enum

Public Function getBraceInside(str As String, _
        Optional paren_type As BracketType = jp_bracket) As String

    Dim pos_start As Integer, pos_end As Integer
    Dim strSTART As String, strEND As String
    getBraceInside = ""

    Select Case paren_type
        Case parenthesis
            strSTART = "(": strEND = ")"
        Case brace
            strSTART = "{": strEND = "}"
        Case bracket
            strSTART = "[": strEND = "]"
        Case quote
            strSTART = "'": strEND = "'"
        Case jp_brace
            strSTART = "「": strEND = "」"
        Case jp_bracket
            strSTART = "【": strEND = "】"
        Case wide_parenthesis
            strSTART = "(": strEND = ")"
        Case wide_brace
            strSTART = "{": strEND = "}"
        Case wide_bracket
            strSTART = "[": strEND = "]"
        Case jp_double_bracket
            strSTART = "『": strEND = "』"
        Case Else
            Err.Raise vbObjectError * myContextID + 515, Description:="unknwon parenthesis type"
    End Select

    pos_start = InStr(str, strSTART)
    pos_end = InStr(str, strEND)
    pos_end = pos_end - pos_start - 1

    getBraceInside = Mid(str, (pos_start + 1), pos_end)
    Debug.Print("String: " & getBraceInside & " distilled from: " & str)
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