' "Module_RecupExistantBase"
Option Explicit

Sub RecupExistantBase(id)
  Dim tbBase(), tbPeche(), tmp()
  Dim espece$
  Dim numCol%, nColEsp%, i%, j%
  Dim pl As Variant
  Dim ctrlEsp As Boolean
  
  tbBase = Range("tb_Base[#all]").Value2
  For i = 1 To UBound(tbBase, 2)
    If tbBase(1, i) = "Total_espece" Then numCol = i: Exit For
  Next i
  
  Sheets("Saisie").ListObjects("tb_Peche").ShowTotals = False
  tbPeche = Range("tb_Peche[#all]").Value2
  For i = 2 To UBound(tbPeche)
    For j = 2 To UBound(tbPeche, 2)
      tbPeche(i, j) = ""
    Next j
  Next i
  
  tmp = FiltreMultiCol(tbBase, id, 1)
  
  For i = 2 To numCol - 1
    If tbBase(1, i) <> "Duree" Then Range(tbBase(1, i)) = tmp(1, i)
  Next i
  
  For i = 1 To UBound(tmp)
    espece = tmp(i, numCol + 1)
    For j = 2 To UBound(tbPeche, 2)
      If tbPeche(1, j) = espece Then
        nColEsp = j: ctrlEsp = True: Exit For
      End If
    Next j
    If ctrlEsp = False Then
      ReDim Preserve tbPeche(1 To UBound(tbPeche), 1 To UBound(tbPeche, 2) + 1)
      tbPeche(1, UBound(tbPeche, 2)) = espece
      nColEsp = UBound(tbPeche, 2)
      Sheets("Saisie").ListObjects("tb_Peche").ListColumns.Add.Name = espece
    End If
    For j = 2 To UBound(tbPeche)
      tbPeche(j, nColEsp) = tmp(i, numCol + j)
    Next j
    ctrlEsp = False
  Next i
  
  ReDim tbBase(1 To UBound(tbPeche) - 1, 1 To UBound(tbPeche, 2))
  For i = 2 To UBound(tbPeche)
    For j = 1 To UBound(tbPeche, 2)
      tbBase(i - 1, j) = tbPeche(i, j)
    Next j
  Next i
  
  Range("tb_Peche").Resize(UBound(tbBase), UBound(tbBase, 2)) = tbBase
  Sheets("Saisie").ListObjects("tb_Peche").ShowTotals = True
  
End Sub

Function FiltreMultiCol(Tbl, cl, colCl)
  Dim Ncol%, i%, k%, n%
  Ncol = UBound(Tbl, 2)
  n = 0
  For i = LBound(Tbl) To UBound(Tbl)
    If cl = Tbl(i, colCl) Then n = n + 1
  Next i
  If n > 0 Then
    Dim b(): ReDim b(1 To n, 1 To Ncol)
    n = 0
    For i = LBound(Tbl) To UBound(Tbl)
      If cl = Tbl(i, colCl) Then
        n = n + 1: For k = 1 To Ncol: b(n, k) = Tbl(i, k): Next k
      End If
    Next i
    FiltreMultiCol = b
  Else
    ReDim b(1 To 1, 1 To 2)
    FiltreMultiCol = b
  End If
End Function
