スナックelve 本店

バツイチ40代女の日記です

ワードのドキュメントと同じフォルダの一番新しいcsvを条件付きで差し込む

・ワードのドキュメント(ファイル)はマクロ有効にしておく
・↑と同じフォルダにcsvを置く
・Normalじゃなくて↑のファイルのマクロに書く

データベース系はホント苦手なんスよ。
ダミーデータはこんな感じ

Option Explicit
'ファイル閉じる前に差し込みなしの文書に(CSVファイル移動したときとかエラー出るから)
Private Sub Document_Close()
    ActiveDocument.MailMerge.MainDocumentType = wdNotAMergeDocument

End Sub

Private Sub Document_Open()
'一番新しいcsvを差し込む
Dim myPath As String: myPath = ThisDocument.Path & "\"
Dim targetFileName As String: targetFileName = Dir(myPath & "*.csv")
Dim newestFileName As String
Dim fileTime As Date:
Dim maxFileTime As Date
Do While targetFileName <> ""
    fileTime = FileDateTime(myPath & targetFileName)
    If fileTime > maxFileTime Then
        newestFileName = targetFileName
        maxFileTime = fileTime
    End If
    targetFileName = Dir
Loop
    'カテゴリBだけ
    Dim SQLstr As String: SQLstr = "SELECT * FROM `" & Replace(newestFileName, ".csv", "") & "$`" & "WHERE カテゴリ = 'B'"

    ActiveDocument.MailMerge.OpenDataSource Name:=myPath & newestFileName, SQLStatement:=SQLstr

End Sub

CSV先に開いたりしてると死ぬ
この辺のエラー処理よくわからん

「'」「`」の使い分け分からん

結果


プレビューするとカテゴリBだけになってるヽ(=´▽`=)ノ