次の2つの条件を満たしたうえでCSVファイルからデータを取り込み、Excelの「Sheet1」に転記するマクロ例です。
- B列(CSV上では2番目の列)に記載されている担当部署が「A部署」「B部署」「C部署」のいずれかである行のみ取り込みたい。
- 不要な列(CSVのJ列からM列に相当する列)を除外して取り込みたい。
Excel上での列名「J〜M」は、1列目がA列、2列目がB列・・・10列目がJ列、11列目がK列、12列目がL列、13列目がM列となるので、1-basedで見ると 10〜13 列になります。
一方、VBAで Split
した配列のインデックスは 0 から始まるため、0-basedでは 9〜12 が該当列です。
マクロの例
Sub ImportCsvFilterAndExcludeCols()
'===【設定項目】=======================================
Dim csvFilePath As String
csvFilePath = "C:\temp\sample.csv" ' CSVファイルのパスを指定
Dim delimiter As String
delimiter = "," ' CSVの区切り文字(カンマ)
' フィルタ対象の部署リスト
Dim deptArray As Variant
deptArray = Array("A部署", "B部署", "C部署") ' このいずれかを含む行だけ取り込む
' 除外する列インデックス(0-based)
' 例:J列〜M列 → 1-basedで 10〜13列 → 0-basedで 9〜12
Dim excludeCols As Variant
excludeCols = Array(9, 10, 11, 12)
' 転記先シート・開始セル
Dim wsDest As Worksheet
Set wsDest = ThisWorkbook.Worksheets("Sheet1") ' 貼り付け先シート
Dim startRow As Long: startRow = 1
Dim startCol As Long: startCol = 1
'===================================================
Dim fileNo As Integer
Dim textLine As String
Dim spl() As String
Dim currentRow As Long
Dim colIndex As Long
' CSVファイルを開く
fileNo = FreeFile
Open csvFilePath For Input As #fileNo
currentRow = startRow
' CSVを1行ずつ読み込み
Do Until EOF(fileNo)
Line Input #fileNo, textLine
' 1行を区切り文字で分割
spl = Split(textLine, delimiter)
'===== [1] 部署フィルタ:B列(0-basedで spl(1))を判定 =====
' B列にある部署が、deptArrayのいずれかに合致するか判定
If IsInArray(spl(1), deptArray) Then
'===== [2] 不要列の除外:J列〜M列(0-basedで 9〜12)をスキップして貼り付け =====
Dim writeCol As Long
writeCol = startCol ' 書き込み開始列
For colIndex = LBound(spl) To UBound(spl)
' 除外する列に含まれていなければ出力
If Not IsInArray(colIndex, excludeCols) Then
wsDest.Cells(currentRow, writeCol).Value = spl(colIndex)
writeCol = writeCol + 1
End If
Next colIndex
currentRow = currentRow + 1 ' 次の行へ
End If
Loop
Close #fileNo
MsgBox "CSVの取込が完了しました。"
End Sub
'----------------------------------------------------------
' 指定した値(variantValue)が配列(arr)内に存在するかを判定する関数
' variantValue : チェック対象(文字列の場合も多い)
' arr : Variant配列(Array(...)で定義)
'----------------------------------------------------------
Private Function IsInArray(ByVal variantValue As Variant, ByVal arr As Variant) As Boolean
Dim i As Long
For i = LBound(arr) To UBound(arr)
If arr(i) = variantValue Then
IsInArray = True
Exit Function
End If
Next i
IsInArray = False
End Function
マクロの流れ
- CSVファイルを1行ずつ読み込む。
Split
関数で行を区切って配列spl
に格納する。- B列(0-basedで
spl(1)
)に含まれる文字列が「A部署」「B部署」「C部署」のいずれかかチェック。 - 条件に合致したら、不要な列(J〜M列: 0-based で 9〜12)をスキップして、その他の列だけを
Sheet1
へ書き込む。 - すべての行を処理したら完了。
コメント