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?

マクロ形式で新規ブックを作成し、保存する方法

Posted at

#マクロ形式で新規ブックを作成し、保存する方法

Sub SaveCopyWithC4C6NameToKensaMae()
    Dim currentPath As String
    Dim saveFolder As String
    Dim sheet As Worksheet
    Dim valueC4 As String
    Dim valueC6 As String
    Dim fileName As String
    Dim fullPath As String

    ' 測定結果シートを取得
    On Error Resume Next
    Set sheet = ThisWorkbook.Sheets("測定結果")
    On Error GoTo 0

    If sheet Is Nothing Then
        MsgBox "シート『測定結果』が見つかりません。", vbExclamation
        Exit Sub
    End If

    ' C4とC6の値を取得
    valueC4 = Trim(sheet.Range("C4").Value)
    valueC6 = Trim(sheet.Range("C6").Value)

    If valueC4 = "" Or valueC6 = "" Then
        MsgBox "C4 または C6 のセルが空です。", vbExclamation
        Exit Sub
    End If

    ' ファイル名を作成(無効文字除去)
    fileName = CleanFileName(valueC4 & "_" & valueC6) & ".xlsm"

    ' 保存元ファイルのパスを取得
    currentPath = ThisWorkbook.Path

    If currentPath = "" Then
        MsgBox "このブックはまだ保存されていません。保存してから実行してください。", vbExclamation
        Exit Sub
    End If

    ' Mac用:スラッシュ(/)でパスを構成
    saveFolder = currentPath & "/検査前"

    fullPath = saveFolder & "/" & fileName

    ' ブックのコピーを保存
    ThisWorkbook.SaveCopyAs fullPath

    MsgBox "『検査前』フォルダにコピーを保存しました:" & vbCrLf & fullPath
End Sub


Function CleanFileName(fileName As String) As String
    Dim invalidChars As Variant
    Dim i As Integer

    ' Windows/Mac共通で使えない文字を_に置き換え
    invalidChars = Array("/", "\", ":", "*", "?", """", "<", ">", "|")

    For i = LBound(invalidChars) To UBound(invalidChars)
        fileName = Replace(fileName, invalidChars(i), "_")
    Next i

    CleanFileName = fileName
End Function

Function CleanFileName(fileName As String) As String
    Dim invalidChars As Variant
    Dim i As Integer

    ' Windows/Mac共通の使用不可文字を _ に置換
    invalidChars = Array("/", "\", ":", "*", "?", """", "<", ">", "|")

    For i = LBound(invalidChars) To UBound(invalidChars)
        fileName = Replace(fileName, invalidChars(i), "_")
    Next i

    CleanFileName = fileName
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?