fork download
  1. Option Explicit
  2.  
  3. Public Sub CSV取り込み()
  4. Const Folder As String = "D:\goo\data9"
  5. Dim dicT As Object
  6. Dim ws As Worksheet
  7.  
  8. Dim path As String
  9. Dim sline As String
  10. Dim head() As String
  11. Dim elms() As String
  12. Dim ConV() As Long
  13. Dim i As Long
  14. Dim wcol As Long
  15. Dim maxcol As Long
  16. Dim key As String
  17. Dim wrow As Long: wrow = 2
  18. Set dicT = CreateObject("Scripting.Dictionary") ' 連想配列の定義
  19. Set ws = Worksheets("Sheet1")
  20. maxcol = ws.Cells(1, Columns.count).End(xlToLeft).Column '1行目の最終列を求める
  21. 'Excelのキーを記憶
  22. For wcol = 1 To maxcol
  23. key = ws.Cells(1, wcol).Value
  24. If key <> "" Then
  25. dicT(key) = wcol
  26. End If
  27. Next
  28. '2行目以降をクリア
  29. ws.Rows("2:" & Rows.count).ClearContents
  30. 'CSVオープン
  31. path = Folder & "\" & "test.csv"
  32. Open path For Input As #1
  33. '1行目を読み込む
  34. Line Input #1, sline
  35. 'キー変換テーブルを作成
  36. head = Split(sline, ",")
  37. ReDim ConV(UBound(head))
  38. For i = 0 To UBound(head)
  39. key = head(i)
  40. ConV(i) = 0
  41. If key <> "" And dicT.exists(key) = True Then
  42. ConV(i) = dicT(key)
  43. End If
  44. Next
  45. '2行目以降を読み込む
  46. Do Until EOF(1)
  47. Line Input #1, sline
  48. elms = Split(sline, ",")
  49. '各列を処理する
  50. For i = 0 To UBound(elms)
  51. 'ヘッダの列数以内を処理
  52. If i <= UBound(head) Then
  53. '変換対象のキーがあれば処理する
  54. If ConV(i) > 0 Then
  55. wcol = ConV(i)
  56. ws.Cells(wrow, wcol).Value = elms(i)
  57. End If
  58. End If
  59. Next
  60. wrow = wrow + 1
  61. Loop
  62. Close #1
  63. MsgBox ("完了")
  64. End Sub
  65.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty