MEMO blog

主に自分用のメモです

フォルダ内のエクセルの文字列を置換

  • みんなで作ったたくさんのエクセルファイル。
  • テンプレート時点で誤記があったせいで全直し。。。
  • クソ面倒なので、嫌いなVBAで置換
Option Explicit

Sub XlsWordReplace()

    Const str_target As String = "FOO"
    Const str_replace As String = "BAR"
    
    'フォルダ選択
    Dim in_dir As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        .InitialFileName = ThisWorkbook.Path  '初期表示フォルダの指定
        
        If .Show = True Then
            in_dir = .SelectedItems(1)
        Else
            Exit Sub
        End If
        
    End With
    Debug.Print (in_dir)
    
    'フォルダ内のエクセルのリスト
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim f As File
    For Each f In fso.GetFolder(in_dir).Files
        If LCase(fso.GetExtensionName(f.Name)) = "xlsx" Then
            Call ReplaceWordInXls(f, str_target, str_replace)
        End If
    Next
    
End Sub

Private Sub ReplaceWordInXls(f As File, tar As String, rep As String)
    Debug.Print (f)
    
    Dim wb As Workbook
    Dim ws As Worksheet
    
    Set wb = Workbooks.Open(f, IgnoreReadOnlyRecommended:=True)
    For Each ws In wb.Worksheets
        Call ws.Cells.Replace(tar, rep)
    Next
    wb.Close (True) '上書き保存

End Sub