Gestion Des Cellules VBA
Transcript of Gestion Des Cellules VBA
-
Gestion des cellules
Accueil
Definir un champ
Positionner le curseur
Cellule Active
Dplacer le curseur
Masquer la Maj de l'cran
Slectionner la rgion courante
Redefinir la taille d'un champ
Slectionner des cellules
particulires
Selectionner la zone utilise dans la
feuille
Union et intersection de champs
Rechercher une information(Find)
Derniere ligne d'un champ
Recherche de date(Find)
Find Accent
Recherche dans tout le classeur
Remplacer une
information(Replace)
Remplacer VRAI FAUX
Nommer les champs par VBA
Fusion de cellules
Champs Multi Zones
-RAZ des cellules de la couleur choisie
-Dcaler les mois
-Supprimer lignes qui existent dj
-Copier les lignes colories
-Copier les lignes manquantes
-Colorie les occurences d'un mot cherch
-Recherche 2 critres
-Diffrence entre 2 BD
-Diffrence entre 2 BD multi-critres
-NettoyageFeuille
-Supprimer des lignes vides
-Suppression de lignes
-Suppression de lignes rapide
-Supprime une ligne sur 2
-Supprimer des doublons
-Complter un champ
-Supprimer les lignes commenant par
-Insre ligne avec copie formules
-Masquage de lignes
-Rcupration d'un champ d'un classeur
ferm
-Rcupration du format des cellules
pointes
-Transforme BD en tableau
-Transforme Tableau en BD
-Transforme fiches en BD
-Transforme ligne en colonne
-Transforme colonne en ligne
-Transforme colonne ligne matricielle
-Colonne en ligne avec 2 niveaux rupture
-Trim rapide
-Slection 1 Ligne sur 2
-Editeur couleur
-Liste des feuilles contenant un mot
cherch
-Reprer les doublons multi-feuilles
-Modification de la couleur de la slection
-Curseur ligne
-Curseur Ligne/Colonne
-Mise en forme d'une BD
Range
Cells
ActiveCell
ScreenUpdating
CurrentRegion
Selection.End
Resize
SpecialCells
UsedRange
Union
Intersect
ScrollArea
Find
SpecialCells
UsedRange
Replace
ScrollRow
ScrollColumn
ScrollArea
Merge-Unmerge
Application.Goto
Exemples
Cellules Synthse
Sup Lignes Vides
Masque Colonnes
Sup Lignes Mot
Suppression Doublons
Replace
ApplicationGotoScroll
Maj BD
Diffrence BD
Compare 2 BD
Fusion 2 Listes
Union 1 ligne Sur 2
Recopie Formule
Comparaison 2 BD
Recherche Mat 2
Critres
Curseur
Union Diff Listes
Recherche Multi-
Zones
Trim Rapide
Nettoie Used Range
Coloriage Formules
InsreLignesGroupe
Comparaison 2BD
ComparaisonBD2
ComparaisonBD4
Find
Find Synthse
Find Dernier.xls
Find Dates.xls
Find Plusieurs
Find Multi-Feuilles
Find Recherche
Accent
Find 2 Criteres
Find Vide Lignes
Merge
Merge UnMerge1
Merge Unmerge2
Merge Colonnes
Ecriture formules
Ecrit Formule Somme
-
Dfinir un champ
Range(champ)
Range permet de spcifier un champ.
Range("B3").Select
Range("D4,F4:G4,D116").Select
Range("D4,F4:G4,D116").Interior.ColorIndex=33
Cells(ligne,Colonne)
Cells(ligne,colonne) reprsente la cellule qui est l'intersection de ligne et de colonne.
Cells(3,2) reprsente le contenu de la cellule qui est l'intersection de la 3e ligne et de la 2e colonne.
Cells(3,2).Select
Range(champ).Cells(ligne,colonne)
La ligne et la colonne sont relatives au dbut du champ spcifi dans Range
Range("B3:D6").cells(1,1).select
Cellule active
ActiveCell
La cellule active se spcifie avec ActiveCell. Sur cet exemple, la variable X prend la valeur de la cellule active et
va scrire en A1
x=ActiveCell.Value
Range("A1").Value=x
Positionner le curseur
Range(champ).Select slectionne le champ spcifi
Range("B3").Select ' Slectionne la cellule B3
[B3].Select ' Slectionne la cellule B3
Range("B3").Offset(1,0).select ' Dplace le curseur une ligne au dessous de B3
Activecell.Offset(0,1).select
Dplacer le curseur
Ecrit Formule
Ecrit Formule2
Ecrit Formule3
Ecrit Formule
SousTotaux
-
Activecell.Offset(nb_lignes,nb_colonnes).Select
Activecell.Offset(nb_lignes,nb_colonnes).Select dplace le curseur du nombre de lignes et de colonnes
spcifis.
Range("A1").Select 'Se positionne en A1
ActiveCell.Offset(0; 1).Select 'se dcale droite dune cellule ActiveCell.Offset(1; 0).Select ' Se dcale en bas dune cellule
Masquer la mise jour de l'cran
Application.ScreenUpDating=True/False
Application.ScreenUpdating=False dsactive la mise jour de l'cran.
Application.ScreenUpdating=True la ractive.
Application.ScreenUpdating=False
....
....
Application.ScreenUpdating=True
Champ.End(xlDown-XlUp-XlToRight-XlToLeft)
champ.End(XlDown) reprsente:
- la dernire cellule d'un bloc de cellules pleines dune colonne (2 minimum) en dplaant le curseur vers le bas.
- ou la prochaine cellule pleine d'un bloc vide en dplaant le curseur vers le bas.
Range("A1").End(xlDown).Select ' positionne sur A4
Range("A1", [A1].End(xlDown)).Select ' slectionne A1:A4
Range("A4").End(xlDown).Select ' positionne sur A7
champ.End(XlUp) reprsente:
- la dernire cellule d'un bloc de cellules pleines dune colonne (2 minimum) en dplaant le curseur vers le haut.
- ou la prochaine cellule pleine d'un bloc vide en dplaant le curseur vers le haut.
Range("A7").End(xlUp).Select ' slectionne A4
Range("A65000").End(xlUp).Select ' slectionne A10
-
champ.End(XlToRight) et champ.End(XlToLeftt) correspondent un dplacement
vers la droite et vers la gauche.
Range("A1").End(xlToRight).Select ' slectionne D1
Slectionner la rgion courante
CurrentRegion
champ.CurrentRegion slectionne les cellules autour du champ spcifi.
Range("A1").CurrentRegion.Select ' slectionne les cellules autour de A1
Range("A1").CurrentRegion.Resize(, 1).Select ' slectionne la premire colonne
Range("A1").currentregion.Select
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select ' Sauf la premire ligne
Range("A1").CurrentRegion.PrintPreview ' Aperu
Range("A1").CurrentRegion.PrintOut ' Impression
Rdfinir la taille d'un champ
Resize(lignes,colonnes)
Redfinit la taille d'un champ.
Range("A1").Resize(1,4).Select ' slectionne A1:D1
Range("A1").CurrentRegion.Select
Selection.Offset(1).Resize(Selection.Rows.Count - 1).Select ' enlve la premire ligne
Slectionner les cellules particulires
Champ.SpecialCells(type,valeur)
-SpecialCells permet de slectionner des cellules particulires. C'est l'quivalent
de la commande Edition/Atteindre.
SpecialCells(xlCellTypeBlanks) Cellules vides
-
Selection.SpecialCells(xlCellTypeVisible)
SpecialCells(xlCellTypeLastCell)
Cellules visibles
Dernire cellule de la feuille
-Si type a la valeur xlCellTypeConstants ou xlCellTypeFormulas, valeur spcifie le type de cellules: nombre,
texte,valeurs logiques, erreurs.
Cells.SpecialCells(xlLastCell).Select ' Slectionne la dernire cellule de la feuille
Cells.SpecialCells(xlCellTypeConstants, 1).Select ' Slectionne les cellules numriques de la feuille
Cells.SpecialCells(xlCellTypeConstants, 2).Select ' Slectionne le texte de la feuille
Cells.SpecialCells(xlCellTypeConstants, 23).Select ' Slectionne les constantes de la feuille
Range("A:A").SpecialCells(xlCellTypeConstants, 23).Select ' Slectionne les constantes de la colonne A
Supprimer les lignes vides en colonne A
On Error Resume Next
Range("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Supprimer les cellules vides en colonne A
[A:A].SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp
Copier les lignes non vides en colonne A sur un autre onglet
[A:A].SpecialCells(xlCellTypeConstants, 23).EntireRow.Copy Sheets(2).[A65000].End(xlUp).Offset(1, 0)
RAZ des zones dverrouilles
Sub raz()
ActiveSheet.Unprotect Password:="moi"
For Each c In Cells.SpecialCells(xlCellTypeConstants, 23)
If c.Locked = False Then c.Value = Empty
Next c
ActiveSheet.Protect Password:="moi"
ActiveSheet.EnableSelection = xlUnlockedCells
End Sub
Slectionner la zone utilise d'une feuille
UsedRange
Slectionne la zone utilise dans la feuille active.
ActiveSheet.UsedRange.Select
Adresse
MsgBox ActiveSheet.UsedRange.Address
Slection de la dernire cellule
-
Range(Split(ActiveSheet.UsedRange.Address, ":")(1)).Select
Union et Intersection de champs
Union(champ1,Champ2,)
Donne l'union de champ1,champ2,...
Union([A2:B2], [A4:B4]).Select
Union([A2:B2], [A4:B4]).Copy [A20]
Copie des cellules pleines de plusieurs champs dans un seul champ
Les cellules sont dans la mme colonne:
Range("A1:A5,A10:A15").SpecialCells(xlCellTypeConstants, 23).Copy [D2]
Les cellules ne sont pas dans la mme colonne:
i = 1
For Each c In Union([A3:B7], [C1:C5], [E3:E7]).SpecialCells(xlCellTypeConstants, 23)
i = i + 1
Cells(i, 7) = c
Next c
-
Slectionne les cellules non verrouilles
Sub SelectNonVer()
Set champ = Nothing
For Each c In ActiveSheet.UsedRange
If Not c.Locked Then
If champ Is Nothing Then
Set champ = c
Else
Set champ = Union(champ, c)
End If
End If
Next c
champ.Select
End Sub
Sub auto_open()
On Error Resume Next
CommandBars("BarreVer").Delete
Dim barre As CommandBar
Dim bouton As CommandBarControl
Set barre = CommandBars.Add(Name:="BarreVer")
barre.Visible = True
Set bouton = CommandBars("BarreVer").Controls.Add(Type:=msoControlButton)
bouton.Style = msoButtonCaption
bouton.OnAction = "SelectNonVer"
bouton.Caption = "Selection cellules non verrouilles"
End Sub
Ajout de listes
-
Sub AjoutListes()
[F2:F1000].ClearContents
Set champ = [A2].CurrentRegion.Offset(1)
For i = 1 To champ.Columns.Count
Range("F65000").End(xlUp).Offset(1).Resize(champ.Rows.Count) = Application.Index(champ.Value, , i)
Next i
Intersect(champ1,champ2,)
Donne l'intersection de champ1,champ2,...
Renvoi Nothing si l'intersection ne comporte aucune cellule.
Intersect(Range("A2:D2"), Range("B1:C5")).Select
Rechercher une information
Find()
Champ.Find(What:=valeur, After:=cellule, LookIn:=xlFormulas/XlValues,
LookAt:= xlPart/XlWhole,
SearchOrder:=xlByRows/XlByColumns,
SearchDirection:=xlNext/XlPrevious,
MatchCase:= True/False,
SearchFormat:=False)
Find Synthse
Recherche un texte dans une champ. Find correspond la commande Edition/Rechercher.
LookAt:= xlPart/XlWhole dfinit si la comparaison se fait sur une partie ou la totalit de la cellule.
Par dfaut, ce paramtre conserve la valeur prcdente.
LookIn:=xlFormulas/XlValues spcifie si la recherche se fait dans la formule ou le rsultat. Par dfaut, ce
-
paramtre conserve la valeur prcdente.
Exemple : On cherche un nom
Mthode 1 (gestion d'erreur)
Sub cherche()
nomCherche = InputBox("Nom cherch? ")
On Error Resume Next
Err = 0
Range("A2:A14").Find(What:=nomCherche, LookIn:=xlValues).Select
If Err = 0 Then
Range(ActiveCell, ActiveCell.End(xlToRight)).Select
Else
MsgBox "Pas trouv"
End If
On Error GoTo 0
End Sub
Mthode 2
Sub cherche2()
nomCherche = InputBox("Nom cherch? ")
Set result = Range("A2:A14").Find(What:=nomCherche, LookIn:=xlValues)
If result Is Nothing Then
MsgBox "Non trouv"
Else
Range(result, result.End(xlToRight)).Select
End If
End Sub
Donne toutes les occurrences :
Sub cherche_plusieurs()
-
[A:C].Interior.ColorIndex = xlNone
nom = InputBox("Nom cherch?")
If nom = "" Then Exit Sub
Set c = [A:A].Find(nom, , , xlWhole)
If Not c Is Nothing Then
premier = c.Address
Do
c.Resize(, 3).Interior.ColorIndex = 4
Set c = [A:A].FindNext(c)
Loop While Not c Is Nothing And c.Address premier
End If
End Sub
Non concordance
Colorie les objets de la colonne A non trouvs dans D2:D5.
NonConcordance
Sub coloriage()
Set typecat = Range("D2:D5")
Set inventaire = Range("A2:A" & [A65000].End(xlUp).Row)
inventaire.Interior.ColorIndex = xlNone
For Each c In inventaire
If typecat.Find(c, MatchCase:=True) Is Nothing Then c.Interior.ColorIndex = 3
Next c
End Sub
Recherche de la dernire ligne ou dernire colonne de la feuille ou d'un champ
Sur cet exemple, nous recherchons la dernire ligne et la dernire colonne de la feuille.
Find Dernier.xls
-
Sub dernireligneFeuille()
Cells.Find("*", , , , xlByRows, xlPrevious).Select
End Sub
Sub dernireColonneFeuille()
Cells.Find("*", , , , xlByColumns, xlPrevious).Select
End Sub
Sub IntersectionDerLigneColonneFeuille()
Cells(Cells.Find("*", , , , xlByRows, xlPrevious).Row, Cells.Find("*", , , ,
xlByColumns, xlPrevious).Column).Select
End Sub
Nombre de lignes et de colonnes de la feuille.
Sub nbLignesFeuille()
MsgBox Sheets(1).Cells.Find("*", , , , xlByRows, xlPrevious).Row & " Lignes"
MsgBox Sheets(1).Cells.Find("*", , , , xlByColumns, xlPrevious).Column & " Colonnes"
End Sub
Sur cet exemple, nous recherchons la dernire ligne et la dernire colonne d'un champ.
Sub dernireligneChamp()
[B6:D10].Find("*", , , , xlByRows, xlPrevious).Select
End Sub
-
Sub dernireColonneChamp()
[B6:D10].Find("*", , , , xlByColumns, xlPrevious).Select
End Sub
Sub IntersectionDerLigneColonneChamp()
Cells([B6:D10].Find("*", , , , xlByRows, xlPrevious).Row, [B6:D10].Find("*", , , , xlByColumns,
xlPrevious).Column).Select
End Sub
Slectionne de la ligne1 la dernire ligne des colonnes D :E
x = "D:E"
Intersect(Range(x), Range("1:1")).Resize(Range(x).Find("*", searchorder:=xlByRows,
SearchDirection:=xlPrevious).Row).Select
Recherche de date
Find Dates.xls
Le format de la date cherche est le mme que le format des dates du champ de recherche
Sub RechercheDateFind()
d = InputBox("Date? jj/mm/aa")
If d "" Then
On Error Resume Next
[L:L].Find(What:=CDate(d), LookIn:=xlValues).Select
If Err 0 Then MsgBox "Inconnu"
End If
End Sub
On adapte le format de la date recherche au format des dates du champ de recherche
Sub RechercheDateFind2()
d = InputBox("Date? jj/mm/aa")
If d "" Then
On Error Resume Next
[N:N].Find(What:=Format(CDate(d), "dddd d mmmm yyyy"), LookIn:=xlValues).Select
If Err 0 Then MsgBox "Inconnu"
End If
End Sub
Avec la fonction Equiv(), le format des dates du champ de recherche n'a pas d'importance
-
Sub RechercheDateColonneEquiv()
d = InputBox("Date?")
If IsDate(d) Then
p = Application.Match(CDbl(CDate(d)), [L2:L10000], 0)
If IsError(p) Then
MsgBox "Inconnu"
Else
[L2].Offset(p - 1, 0).Select
End If
Else
MsgBox "n'est pas une date"
End If
End Sub
Remplace les abrviations slectionnes par les libells
ChercheRemplaceFind
Sub traduc()
For Each c In Selection
a = Split(c, " ")
For i = LBound(a) To UBound(a)
Set temp = [abrev].Find(what:=a(i), LookAt:=xlWhole)
If Not temp Is Nothing Then a(i) = temp.Offset(, 1).Value
Next i
c.Value = Join(a, " ")
Next
End Sub
ou
Sub traduc2()
abr = [abrev].Value ' lecture dans un tableau
lib = [abrev].Offset(, 1).Value ' lecture dans un tableau
For Each c In Selection
a = Split(c, " ")
For i = LBound(a) To UBound(a)
p = Application.Match(a(i), abr, 0)
-
If Not IsError(p) Then a(i) = lib(p, 1)
Next i
c.Value = Join(a, " ")
Next
End Sub
Recherche de nombres avec Find
ValCherche = InputBox("Valeur recherche")
If IsNumeric(ValCherche) Then ValCherche = CDbl(ValCherche)
Cells.Find(What:=ValCherche).Activate
Colorie les occurences du mot cherch dans un champ
ChercheMotChamp
Colorie les occurences du mot cherch dans un champ
ChercheMot
-
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$2" Then
If [iv1] = "" Then
[A4:A1000].Copy [IV4]
[iv1] = "archiv"
Else
[IV4:IV1000].Copy [A4]
End If
mot = Target
For Each c In [A4:A1000]
p = 1
Do While p > 0
p = InStr(p, UCase(c), UCase(mot))
If p > 0 Then
c.Characters(p, Len(mot)).Font.ColorIndex = 3
p = p + Len(mot)
End If
Loop
Next c
End If
End Sub
Nettoyage d'une feuille
Parfois, le UsedRange d'une feuille (Maj+Ctrl+fin) comporte des lignes et des colonnes aprs la dernire cellule
pleine.
Pour supprimer les lignes et colonnes inutilises de la feuille:
- Nettoie Used Range -
Sub SupLigneColTrop()
Range(Cells(Cells.Find("*", , , , xlByColumns, xlPrevious).Column + 1), Cells(1, 254)).EntireColumn.Delete
-
Range(Cells(Cells.Find("*", , , , xlByRows, xlPrevious).Row + 1, 1), Cells(65536, 1)).EntireRow.Delete
End Sub
Sub VisuUsedRange()
ActiveSheet.UsedRange.Select
End Sub
Recherche 2 critres
Recherche matricielle 2 critres
On suppose que le nom cherch est en F2 et le prnom en G2 . Nom et Prenom sont 2 champs nomms.
RechercheMat2Critres
Sub Recherche()
p = Evaluate("match(1,(nom=F2)*(prenom=G2),0)")
If Not IsError(p) Then
Range("nom")(1).Offset(p - 1).Select
Else
MsgBox "inconnu"
End If
End Sub
Le nom et le prnom sont dans des variables n et P.
Sub Recherche2()
n = "Martin"
-
p = "Daniel"
pos = Evaluate("match(1,(nom=""" & n & """)*(prenom=""" & p & """),0)")
If Not IsError(pos) Then
Range("nom")(1).Offset(pos - 1).Select
Else
MsgBox "inconnu"
End If
End Sub
Recherche 2 critres dans un tableau
Reherche2crit
Sub RechercheMultiCritres()
n = "titi"
p = "Jean"
a = [NOM].Resize(, 3) ' recherche dans tableau + rapide
For i = 1 To UBound(a, 1)
If a(i, 1) = n And a(i, 2) = p Then
MsgBox a(i, 3)
End If
Next i
End Sub
Recherche 2 critres avec find
Sub FindMultiCritres()
n = "titi"
p = "jean"
Set c = [NOM].Find(n, LookIn:=xlValues, LookAt:=xlWhole)
If Not c Is Nothing Then
premier = c.Address
Set temp = c.Offset(, 1)
Do
Set temp = Union(temp, c.Offset(, 1))
Set c = [NOM].FindNext(c)
Loop While Not c Is Nothing And c.Address premier
End If
'-- recherche prnom
Set c = temp.Find(p, LookIn:=xlValues, LookAt:=xlWhole)
If Not c Is Nothing Then
MsgBox c.Offset(, 1)
Else
MsgBox "non trouv"
End If
End Sub
Recherche Find avec caractres accentus
Cration d'une BD partir de fiches
-
On recherche la position du mot prnom dans les cellules. Prnom est crit avec ou sans accent.
On remplace la recherche du mot Prnom par la recherche de Pr?nom.
Find Accent
Sub CreBD()
Set f = Sheets("BD")
ligneBD = 2
For Each c In f.[A:A].SpecialCells(xlCellTypeConstants, 23).Areas
p = InStr(c.Cells(1, 1), ":") + 1
f.Cells(ligneBD, 3) = Trim(Mid(c.Cells(1, 1), p))
f.Cells(ligneBD, 4) = cherche("Pr?nom", c)
f.Cells(ligneBD, 5) = cherche("Adresse", c)
f.Cells(ligneBD, 6) = cherche("Tph", c)
ligneBD = ligneBD + 1
Next c
End Sub
Function cherche(quoi, o)
Set rsultat = o.Find(quoi, LookIn:=xlValues, LookAt:=xlPart)
If Not rsultat Is Nothing Then
p = InStr(rsultat.Value, ":") + 1
If p > 0 Then cherche = Trim(Mid(rsultat.Value, p))
End If
End Function
Recherche de toutes les cellules qui contiennent un mot accentu
On recherche toutes les cellules qui contiennent tudiant avec ou sans accent.
On remplace par le joker ?
valeurChercheJoker = "?tudiant"
Find Accent (0,04 s pour 25.000 lignes)
Find Recherche Accent
-
Sub FindAccent()
valeurCherche = "tudiant"
valeurChercheJoker = "?tudiant"
Set champRecherche = [A:A]
Set rsultat = champRecherche.Find(valeurChercheJoker, LookIn:=xlValues, LookAt:=xlPart)
If Not rsultat Is Nothing Then
premier = rsultat.Address
Do
If sansAccent(rsultat.Value) = sansAccent(valeurCherche) Then rsultat.Interior.ColorIndex = 4
Set rsultat = champRecherche.FindNext(rsultat)
Loop While Not rsultat Is Nothing And rsultat.Address premier
End If
End Sub
Function sansAccent(chaine)
codeA = ""
codeB = "EEEEOeeeeacuouii"
temp = chaine
For i = 1 To Len(temp)
p = InStr(codeA, Mid(temp, i, 1))
If p > 0 Then Mid(temp, i, 1) = Mid(codeB, p, 1)
Next
sansAccent = temp
End Function
Avec une recherche squentielle (0,75s pour 25.000 lignes)
Sub RechSeqAccent()
valeurCherche = "tudiant"
For Each c In Range([A2], [A65000].End(xlUp))
If sansAccent(c) = sansAccent(valeurCherche) Then c.Interior.ColorIndex = 4
Next c
End Sub
Recherche d'un mot dans tout le classeur
Donne la liste des feuilles d'un classeur contenant le mot cherch.
Recherche mot dans tout le classeur
-
Private Sub B_ok_Click()
If Me.TextBox1 = "" Then Exit Sub
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Temp").Delete
On Error GoTo 0
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = "Temp"
[A1] = Me.TextBox1
ligne = 2
For i = 1 To Sheets.Count - 1
With Sheets(i).Cells
If IsDate(Me.TextBox1) Then
Set c = .Find(CDate(Me.TextBox1), LookIn:=xlValues, LookAt:=xlPart)
Else
Set c = .Find(Me.TextBox1, LookIn:=xlValues, LookAt:=xlPart)
End If
If Not c Is Nothing Then
premier = c.Address
Do
temp = [A1]
Sheets("temp").Hyperlinks.Add Anchor:=Sheets("temp").Cells(ligne, 1), _
Address:="", SubAddress:="'" & Sheets(i).Name & "'" & "!" & c.Address, TextToDisplay:=temp
Cells(ligne, 2) = Sheets(i).Name
Cells(ligne, 3) = c.Address
ligne = ligne + 1
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address premier
End If
End With
Next i
End Sub
Supprimer les lignes vides
Cellules vides dans la colonne A
On Error Resume Next
-
[A:A].SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Cellules vides sur toutes les colonnes
For i = [A65000].End(xlUp).Row To 1 Step -1
If Application.CountA(Rows(i)) = 0 Then Rows(i).Delete
Next i
Cellules vides de la colonne B la colonne H
SupLignesVidesColonne
Sub suplignesvides()
Set f = Sheets("feuil1")
Application.ScreenUpdating = False
For i = f.[A65000].End(xlUp).Row To 2 Step -1
If Application.CountA(Range(f.Cells(i, "b"), f.Cells(i, "h"))) = 0 Then f.Rows(i).Delete
Next i
End Sub
Sub supLignesVides2()
Application.ScreenUpdating = False
Columns("b:b").Insert Shift:=xlToRight
Range("B2:B" & [A65000].End(xlUp).Row).FormulaR1C1 = "=IF(COUNTA(RC[1]:RC[7])=0,""sup"",0)"
Range("B2:B65000").SpecialCells(xlCellTypeFormulas, 2).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Suppression des lignes et colonnes vides
For i = ActiveSheet.UsedRange.Rows.Count To 1 Step -1
If Application.CountA(Rows(i)) = 0 Then Rows(i).Delete
Next i
-
For i = ActiveSheet.UsedRange.Columns.Count To 1 Step -1
If Application.CountA(Columns(i)) = 0 Then Columns(i).Delete
Next i
Slection de lignes
On veut slectionner les lignes des annes 2008.
Selection Lignes 2008
Sub Selection2008()
Range("E2:E" & [A65000].End(xlUp).Row).FormulaR1C1 = "=IF(YEAR(RC[-1])=2008,""ok"")"
[E:E].SpecialCells(xlCellTypeFormulas, 2).EntireRow.Select
[E:E].ClearContents
End Sub
Suppression de lignes
Suppression classique
On supprime les lignes qui contiennent xxxx dans la premire colonne
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
For i = [A65000].End(xlUp).Row To 1 Step -1
If Cells(i, 1) = "xxxx" Then Rows(i).Delete Shift:=xlUp
-
Next i
Application.Calculation = xlCalculationAutomatic
ou
[A:A].Replace "xxxx", ""
[A:A].SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Avec le filtre automatique
SupLignesFiltreAuto
Sub SupLignesFiltreAuto()
[A1].AutoFilter Field:=1, Criteria1:="xxxx"
Range("_FilterDataBase").Offset(1, 0).Resize(Range("_FilterDataBase"). _
Rows.Count - 1).SpecialCells(xlCellTypeVisible).Delete Shift:=xlUp
[A1].AutoFilter
End Sub
Avec le filtre labor
Supprime les exclus - xx yy zz - ( 0,1 S pour 10.000 lignes).
Au lieu de supprimer les lignes, on recopie dans une autre feuille ce qui ne doit pas tre supprim.
SupLignesFiltre
Sub sup_filtre()
Sheets("result").[A:C].Clear
Sheets("BD").Range("A1:C12000").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("BD").Range("F1:F2"), CopyToRange:=Sheets("result").Range("A1")
Sheets("result").Select
End Sub
-
A l'aide d'une colonne intermdiaire:
SupLignes
Sub supLignes()
Application.ScreenUpdating = False
Columns("b:b").Insert Shift:=xlToRight
Range("B2:B" & [A65000].End(xlUp).Row).FormulaR1C1 = "=IF(RC[-1]=""xxxx"",""sup"",0)"
Range("B2:B65000").SpecialCells(xlCellTypeFormulas, 2).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Suppression rapide
On regroupe les lignes supprimer en fin de tableau.
La suppression des lignes ainsi regroupes en fin de tableau est trs rapide.
L'ordre initial des lignes n'est pas modifi.
-on repre les lignes supprimer avec la valeur Sup
-on tri les lignes . Les lignes contenant Sup se retrouvent la fin
-on supprime les lignes contenant Sup
(0,2sec pour 20.000 lignes)
SupLignesRapide
SupLignesRapideCouleur
-
Sub supLignesRapide()
Application.ScreenUpdating = False
Columns("b:b").Insert Shift:=xlToRight
Range("B2:B" & [A65000].End(xlUp).Row).FormulaR1C1 = "=IF(RC[-1]=""xxxx"",""sup"",0)"
[B:B].Value = [B:B].Value
[A2].CurrentRegion.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess
On Error Resume Next
Range("B2:B65000").SpecialCells(xlCellTypeConstants, 2).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Autre mthode (0,15 sec pour 20.000 lignes)
Sub supLignesRapide2()
Application.ScreenUpdating = False
a = Range("A2:A" & [A65000].End(xlUp).Row)
For i = LBound(a) To UBound(a)
If a(i, 1) "xxxx" Then a(i, 1) = 0 Else a(i, 1) = "sup"
Next i
Columns("b:b").Insert Shift:=xlToRight
[B2].Resize(UBound(a)) = a
[A2].CurrentRegion.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess
On Error Resume Next
Range("B2:B65000").SpecialCells(xlCellTypeConstants, 2).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Supprimer des lignes commenant par
Sub SupLignes3()
Application.ScreenUpdating = False
For i = [A65000].End(xlUp).Row To 1 Step -1
If Left(Cells(i, 1), 4) "SCVT" Then Rows(i).Delete
Next i
End Sub
Suppression de lignes sur 3 colonnes
-
For i = [A65000].End(xlUp).Row To 1 Step -1
If Cells(i, 1) = "" Then Cells(i, 1).Resize(1, 3).Delete Shift:=xlUp
Next i
Suppression de cellules vides
[A:D].SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp
Supprime une ligne sur 2 (rapide)
Sup1LigneSur2
Sub supLignes1sur2()
Application.ScreenUpdating = False
Columns("b:b").Insert Shift:=xlToRight
Range("B2:B" & [A65000].End(xlUp).Row).FormulaR1C1 = "=if(MOD(ROW(),2)=1,""sup"",0)"
Range("B2:B65000").SpecialCells(xlCellTypeFormulas, 2).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Sub supLignes1sur2Rapide()
Application.ScreenUpdating = False
Columns("b:b").Insert Shift:=xlToRight
Range("B2:B" & [A65000].End(xlUp).Row).FormulaR1C1 = "=if(MOD(ROW(),2)=1,""sup"",0)"
[B:B].Value = [B:B].Value
[A2].CurrentRegion.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess
Range("B2:B65000").SpecialCells(xlCellTypeConstants, 2).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Masquage de lignes
On masque les lignes si cellules vides dans colonne B
-
On Error Resume Next
Range("b:b").SpecialCells(xlCellTypeBlanks).EntireRow.Hidden = True
On masque les lignes si cellules vides dans toutes les colonnes
For i = 1 To [A65000].End(xlUp).Row
If Application.CountA(Rows(i)) = 0 Then Rows(i).Hidden = True
Next i
Pour faire apparatre toutes les lignes de la feuille
Cells.EntireRow.Hidden = False
Masquer des groupes de lignes ou de colonnes
Range("5:10,15:20,25:30").EntireRow.Hidden = True
Range("B:D,G:J").EntireColumn.Hidden = True
Insre une ligne vide entre les lignes
Range("A65000").End(xlUp).Select
For i = 1 To Selection.currentregion.Rows.Count - 1
ActiveCell.EntireRow.Insert
ActiveCell.Offset(-1, 0).Select
Next
Range("A2:A1000").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Suppression de doublons
Sub supDoublonsTradi()
Application.ScreenUpdating = False
-
Application.Calculation = xlCalculationManual
[A1].Sort Key1:=Range("A2"), Order1:=xlAscending, Header:=xlGuess
For i = [A65000].End(xlUp).Row To 2 Step -1
If Cells(i, 1) = Cells(i - 1, 1) Then Rows(i).Delete
Next i
Application.Calculation = xlCalculationAutomatic
End Sub
Suppression de doublons rapide
Lorsque le nombre de lignes devient important et si le taux de suppression est lev, la mthode ci dessous
est plus rapide( 1 s pour 10000 lignes contre 7 s).
Principe: -Formule =SI(A2=A1;1;0) pour reprer les doublons avec la valeur 1
-Tri pour regrouper les lisgnes supprimer
-Remplacer 1 par un vide
-Slection et Suppression
- SupDoublonsRapide -
Sub SupRapide1Critere()
Application.ScreenUpdating = False
[A1].Sort Key1:=Range("A2"), Order1:=xlAscending, _
Header:=xlGuess
Columns("b:b").Insert Shift:=xlToRight
[B1] = "ColB"
[B2].FormulaR1C1 = "=IF(RC[-1]=R[-1]C[-1],1,0)"
[B2].AutoFill Destination:=Range("B2:B" & [A65000].End(xlUp).Row)
[B:B].Value = [B:B].Value
[A2].CurrentRegion.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess
[B:B].Replace What:="1", Replacement:="", LookAt:=xlPart
Range("B2:B65000").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Sub SupRapide2CriteresColAColB()
-
Application.ScreenUpdating = False
[A1].Sort Key1:=Range("A2"), Order1:=xlAscending, _
Key2:=Range("B2"), Order2:=xlAscending, _
Header:=xlGuess
Columns("b:b").Insert Shift:=xlToRight
[B1] = "ColB"
[B2].FormulaR1C1 = "=IF(AND(RC[-1]=R[-1]C[-1],RC[+1]=R[-1]C[+1]),1,0)"
[B2].AutoFill Destination:=Range("B2:B" & [A65000].End(xlUp).Row)
[B:B].Value = [B:B].Value
[A2].CurrentRegion.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess
[B:B].Replace What:="1", Replacement:="", LookAt:=xlPart
Range("B2:B65000").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Columns("b:b").Delete Shift:=xlToLeft
End Sub
Suppression de doublons sans modifier l'ordre
Sur colonne A
Sub supdoublons()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set champ = Range("A1:A" & [A65000].End(xlUp).Row)
For i = [A65000].End(xlUp).Row To 1 Step -1
If Application.CountIf(champ, Cells(i, 1)) > 1 Then
Cells(i, 1).Delete Shift:=xlUp ' ou Rows(i).Delete
End If
Next i
Application.Calculation = xlAutomatic
End Sub
Sur colonne A et C
Rapide si taux de suppression faible. 2 s pour 10.0000 lignes et taux suppression 5%
Sub OrdreRespectDictionary()
Set MonDico = CreateObject("Scripting.Dictionary")
Application.ScreenUpdating = False
i = 2
Do While Cells(i, "A") ""
If Not MonDico.Exists(Cells(i, "A") & Cells(i, "C")) Then
MonDico.Add Cells(i, "A") & Cells(i, "C"), Cells(i, "A") & Cells(i, "C")
-
i = i + 1
Else
Rows(i).EntireRow.Delete
End If
Loop
End Sub
Complter un champ
[A1:A20].SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
[A1:A20].Value = [A1:A20].Value
Autre cas
[A1].CurrentRegion.Resize(, 1).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
[A1].CurrentRegion.Resize(, 1).Value = [A1].CurrentRegion.Resize(, 1).Value
Insre une ligne la position du curseur et copie les formules
Recopie Formule
Sub InsreCopieLigne()
-
ActiveCell.EntireRow.Insert
Rows(ActiveCell.Row + 1).Copy Rows(ActiveCell.Row)
On Error Resume Next
Rows(ActiveCell.Row).SpecialCells(xlCellTypeConstants, 23).ClearContents
End Sub
Recopie la dernire ligne et ne laisse que les formules
Sub RecopieDerniereLigne()
[A65000].End(xlUp).Offset(1, 0).Select
ActiveCell.Offset(-1, 0).EntireRow.Copy ActiveCell
On Error Resume Next
Rows(ActiveCell.Row).SpecialCells(xlCellTypeConstants, 23).ClearContents
End Sub
Pour affecter une macro au clic droit sur cette feuille :
Private Sub Worksheet_Activate()
Set temp = CommandBars("cell").Controls.Add
temp.Caption = "Recopie dernire ligne"
temp.OnAction = "recopie"
temp.FaceId = 120
temp.BeginGroup = True
End Sub
Private Sub Worksheet_Deactivate()
Application.CommandBars("Cell").Reset
End Sub
Remplacer une information
Replace()
Champ.Replace What:=valeur, Replacement:=valeur,
LookAt:=xlPart/XlWhole,
SearchOrder:=xlByRows/XlByColumns,
MatchCase:=False, SearchFormat:=True/False,
ReplaceFormat:=True/False
Remplace une chane de caractres par une autre chane.
Range(A1:A10).Replace " ", ""
Caractres spciaux:
* : remplace un nombre inddermin de caractres
? : remplace 1 caractre
S'il y a un caractre spcial dans la chane, utiliser ~ devant le caractre spcial:
-
Sur cet exemple, on remplace le caractre * par une chane vide
aaa*aaa
bbbbb*bb
cc*ddd
Range(A1:A10).Replace "~* ", ""
Supprime les lignes se terminant par DE
mmm
mmmDE
mmm
mmm
mmmDE
mmm
[A:A].Replace What:="*DE", Replacement:="", LookAt:=xlWhole
On Error Resume Next
[A:A].SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Remplacer VRAI/FAUX
Pour remplacer les valeurs boolennes VRAI et FAUX dans une feuille
Cells.Replace What:=True, Replacement:="x"
Cells.Replace What:=False, Replacement:=""
Positionnement du curseur
ScrollRow=ligne
ScrollColumn=colonne
ScrollRow positionne la ligne active en haut de l'cran.
ScrollColumn positionne la colonne active gauche de l'cran.
Sur cet exemple, la cellule active est positionne en haut de l'cran
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveWindow.ScrollRow = ActiveCell.Row
End Sub
ScrollColumn
-
Sur cet exemple, la ligne active est positionne au milieu de l'cran.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If ActiveCell.Row > 12 Then
ActiveWindow.ScrollRow = ActiveCell.Row - 12
End If
End Sub
Positionne le curseur sur Activit suivant/prcdent
PositionneSuivant
Sub positionneActivitSuivant()
On Error Resume Next
Range(Cells(2, ActiveCell.Column + 1), Cells(2, 255)).Find(What:="Activit",
SearchDirection:=xlNext).Select
ActiveWindow.ScrollColumn = ActiveCell.Column
End Sub
Sub positionneActivitPrcdent()
On Error Resume Next
Range(Cells(2, ActiveCell.Column - 1), Cells(2,
"A")).Find(What:="Activit", SearchDirection:=xlPrevious).Select
ActiveWindow.ScrollColumn = ActiveCell.Column
End Sub
Application.goto(rfrence,scroll)
Slectionne la rfrence spcifie.
Si Scroll=True, le coin suprieur gauche de la rfrence apparat dans le coin suprieur gauche de la fentre.
Application.Goto Reference:=Sheets(1).Range("A20"), scroll:=True
Positionne le curseur sur la date du jour ou la suivante La mme date peut apparatre plusieurs fois
-
Sub auto_open()
p = Application.Match(CDbl(Date), [A1:A100], 1)
Application.Goto [A1].Offset(p - 1 + IIf(Cells(p, 1) = Date, 0, 1)), scroll:=True
End Sub
Dfinir la zone utilisable par l'oprateur
ScrollArea=champ
Dfinit le champ utilisable par l'utilisateur.
Sheets(1).ScrollArea = "a1:f10"
Zone visible l'cran
champVisible = ActiveWindow.VisibleRange.Address
premLigne = ActiveWindow.VisibleRange.Row
derLigne = ActiveWindow.VisibleRange.Rows.Count
premCol = ActiveWindow.VisibleRange.Column
derCol = ActiveWindow.VisibleRange.Columns.Count
Commentaire dans une cellule
Ci dessous, nous crons un commentaire dans une cellule.
With Sheets(1).[A1]
If .Comment Is Nothing Then
.AddComment ' Cration commentaire
.Comment.Shape.OLEFormat.Object.Font.Name = "Tverdana"
.Comment.Shape.OLEFormat.Object.Font.Size = 7
.Comment.Shape.OLEFormat.Object.Font.FontStyle = "Normal"
End If
.Comment.Text Text:="Ceci est un commentaire..."
.Comment.Shape.TextFrame.AutoSize = True
.Comment.Visible = False
End With
Nommer les champs par VBA
-
Sub NommerChamps()
Range("A1").Select
For Each c In Range(ActiveCell, Cells(ActiveCell.Row, 254).End(xlToLeft))
If Not IsEmpty(c.Offset(1, 0)) Then
ActiveWorkbook.Names.Add Name:=c, RefersTo:="=" & Range(c.Offset(1, 0), c.End(xlDown)).Address
End If
Next
End Sub
Sub NommerChampsDynamique()
Range("A1").Select
For Each c In Range(ActiveCell, Cells(ActiveCell.Row, 254).End(xlToLeft))
If Not IsEmpty(c.Offset(1, 0)) Then
ActiveWorkbook.Names.Add Name:=c, RefersTo:= _
"=OFFSET(" & c.Address & ",,,COUNTA(" & c.EntireColumn.Address & ")-1)"
End If
Next
End Sub
Modification de la police dans une cellule
Cells(1, 1) = "Ceci est un essai de caractres en gras dans une cellule...."
Cells(1, 1).Characters(Start:=4, Length:=10).Font.FontStyle = "Gras"
Fusionner des cellules
Champ.Merge
Champ.MergeCells=True/False
Champ.Unmerge
Champ.Merge fusionne les cellules du champ spcifi.
Sur cet exemple, nous fusionons 2 colonnes dans une seule en conservant les donnes des 2 colonnes
Sub essai()
Application.DisplayAlerts = False
Lignedpart = 2
colonneDpart = 2
n = 4
For lig = Lignedpart To Lignedpart + n
Cells(lig, colonneDpart) = Cells(lig, 2) & Cells(lig, colonneDpart + 1)
Cells(lig, colonneDpart).Resize(1, 2).Merge
Next lig
End Sub
-
Fusion de 2 colonnes sans Merge
0,3 secondes pour 20.000 lignes
Sub FusionColBColCSansMerge()
Application.ScreenUpdating = False
lignedpart = 2
colonnedpart = 2
n = 20000
a = Cells(lignedpart, colonnedpart).Resize(n, 2).Value
For i = LBound(a) To UBound(a)
a(i, 1) = a(i, 1) & " " & a(i, 2)
Next i
Cells(lignedpart, colonnedpart).Resize(n, 2) = a
Cells(lignedpart, colonnedpart + 1).Resize(n).ClearContents
End Sub
Sur cet exemple, les codes articles identiques sont fusionns dans une seule cellule.
Avant Aprs
Sub merge()
Application.DisplayAlerts = False
i = 2
Do While Cells(i, 1) ""
m = i
Do While Cells(i, 1) = Cells(m, 1)
i = i + 1
Loop
Cells(m, 1).Resize(i - m).VerticalAlignment = xlTop
Cells(m, 1).Resize(i - m).MergeCells = True
Loop
End Sub
Sub Unmerge()
Range([A2], [a65000].End(xlUp)).Unmerge
Range([b2], [b65000].End(xlUp)).Offset(0, -1).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
Range([A2], [a65000].End(xlUp)).Value = Range([A2], [a65000].End(xlUp)).Value
End Sub
Pour obtenir le champ complet d'une cellule fusionne
-
If [B5].MergeCells Then MsgBox [B5].MergeArea.Address
Champs multi zones
La fonction RechercheMZ(valCherche, champRech As Range, ChampRetour) donne une valeur associe
une valeur cherche
Recherche Multi-Zones
=RechercheMZ(K2;(A2:A7;D2:D5;G2:G7);(B2:B7;E2:E5;H2:H7))
Si les champs ont ts nomms:
=RechercheMZ(K2;Noms;Salaire)
Function RechercheMZ(valCherche, champRech As Range, ChampRetour)
Application.Volatile
For i = 1 To champRech.Areas.Count
For j = 1 To champRech.Areas(i).Count
If valCherche = champRech.Areas(i)(j) Then
RechercheMZ = ChampRetour.Areas(i)(j)
Exit Function
End If
Next j
Next i
RechercheMZ = "pas trouv"
End Function
Exemples
RAZ les cellules de la couleur choisie
Slectionner le champ puis excuter la macro.
RazCouleur
-
Sub razcoul()
On Error Resume Next
Set x = Application.InputBox("cliquer sur une cellule avec la couleur effacer", Type:=8)
If Err = 0 Then
For Each c In Selection
If c.Interior.ColorIndex = x.Interior.ColorIndex Then c.Value = Empty
Next c
End If
End Sub
Dcale les mois vers la gauche
Glissant
Sub glissant()
'-- dcalage des 11 derniers mois sur le premier
Range("C1:M7").Cut Destination:=Range("B1")
'--- recopie la dernire colonne droite
Range("L1:L7").AutoFill Destination:=Range("L1:M7"), Type:=xlFillDefault
Range("M2:M7").ClearContents
'---- Prend le format de la colonne D et le copie en E
Range("b1:b7").Copy
Range("L1").PasteSpecial Paste:=xlFormats
Range("m2").Select
Cells.EntireColumn.AutoFit
End Sub
On veut supprimer les lignes qui existent dj dans l'onglet BD1
On n'utilise pas de colonne intermdiaire
-
Sub SupDoublons()
Range("a2").Select
Do While ActiveCell ""
If Not IsError(Application.Match(ActiveCell, Application.Index(Range("base"), , 1), 0)) _
And Not IsError(Application.Match(ActiveCell.Offset(0, 1), Application.Index(Range("base"), , 2), 0)) Then
ActiveCell.EntireRow.Delete
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
End Sub
MEFC:
=SOMMEPROD((INDEX(Base;;1)=$A2)*(INDEX(Base;;2)=$B2)*(INDEX(Base;;1)"")*1)>0
On utilise une colonne intermdiaire(colonne C)
Sub SupDoublons2()
Range("C2").Select
ActiveCell.FormulaR1C1 = "=SUMPRODUCT((INDEX(Base,,1)=RC1)*(INDEX(Base,,2)=RC2)*1)>0"
ActiveCell.Copy Range(ActiveCell, ActiveCell.Offset(0, -1).End(xlDown).Offset(0, 1))
For Each c In Range(ActiveCell, ActiveCell.End(xlDown))
If c.Value = True Then c.EntireRow.Delete
Next c
Range(ActiveCell, ActiveCell.End(xlDown)) = Empty
End Sub
On veut copier en K2 les lignes surlignes en couleur Orange(couleur 44)
-
Sub Archives1()
[K2:N65000].ClearContents
ligneRecap = 1
For i = 2 To [a65000].End(xlUp).Row
If Cells(i, 1).Interior.ColorIndex = 44 Then
ligneRecap = ligneRecap + 1
Cells(i, 1).Resize(1, 4).Copy Cells(ligneRecap, 11)
End If
Next i
End Sub
Vers un autre onglet
Sub Archives2()
Sheets("Archives").Range("A2:F65000").ClearContents
ligneRecap = 1
For i = 2 To [a65000].End(xlUp).Row
If Cells(i, 1).Interior.ColorIndex = 44 Then
ligneRecap = ligneRecap + 1
Cells(i, 1).Resize(1, 4).Copy Sheets("Archives").Cells(ligneRecap, 1)
End If
Next i
End Sub
Copie de lignes manquantes dun classeur dans un autre
On ajoute mois2.xls les lignes de mois1.xls manquantes dans mois2.xls
MFC:=NB.SI(nom1;A2)>0
MFC:=ET(NB.SI(nom2;A2)=0;A2"")
-
Sub CopieManque()
Sheets("BD").Select
Range("A2").Select
ligne = Workbooks("mois2.xls").Sheets("BD").[A65000].End(xlUp).Row + 1
Do While ActiveCell ""
If IsError(Application.Match(ActiveCell, Workbooks("mois2.xls").Sheets("BD").Range("nom"), 0)) Then
Range(ActiveCell, ActiveCell.Offset(0, 1)).Copy Workbooks("mois2.xls").Sheets("BD").Cells(ligne, 1)
ligne = ligne + 1
End If
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Diffrence entre 2 fichiers
On veut connatre les produits qui existent dans Mois1.xls et qui n'existent pas dans Mois2.xls
Sub DiffFich1Fich2()
ligneEcrit = 2
nblignes = Workbooks("mois1.xls").Sheets("BD").[A65000].End(xlUp).Row + 1
For i = 2 To nblignes
x = Workbooks("mois1.xls").Sheets("BD").Cells(i, 1)
If IsError(Application.Match(x, Workbooks("mois2.xls").Sheets("BD").Range("nom"), 0)) Then
Cells(ligneEcrit, 1) = x
ligneEcrit = ligneEcrit + 1
End If
-
Next i
End Sub
Sub DiffFich2Fich1()
ligneEcrit = 2
nblignes = Workbooks("mois2.xls").Sheets("BD").[A65000].End(xlUp).Row + 1
For i = 2 To nblignes
x = Workbooks("mois2.xls").Sheets("BD").Cells(i, 1)
If IsError(Application.Match(x, Workbooks("mois1.xls").Sheets("BD").Range("nom"), 0)) Then
Cells(ligneEcrit, 2) = x
ligneEcrit = ligneEcrit + 1
End If
Next i
End Sub
Comparaison de bases multi-critres avec Array()
Sur cet exemple, nous transfrons les BD dans des tableaux tnom(),tprenom(),tage() pouracclrer la
comparaison. Comparaison
Sub compareBD()
ligne = 2
tnom = [NomBD2]
tprenom = [prenomBD2]
tage = [ageBD2]
For i = 1 To Range("NomBD1").Count
n = Range("NomBD1")(i)
p = Range("PreNomBD1")(i)
a = Range("AgeBD1")(i)
tmoin = False
If n "" Then
For k = 1 To Range("nomBD2").Count
If tnom(k, 1) = n And tprenom(k, 1) = p And tage(k, 1) = a Then tmoin = True
Next k
If Not tmoin Then
Sheets("diff").Cells(ligne, 1) = n
Sheets("diff").Cells(ligne, 2) = p
Sheets("diff").Cells(ligne, 3) = a
ligne = ligne + 1
-
End If
End If
Next i
End Sub
Rcupration d'un champ d'un classeur ferm
Rcupre un champ d'un classeur ferm
Sub LitClasseurFerm()
ChampOuCopier = "A1:A4"
Chemin = ThisWorkbook.Path
Fichier = "stock.xls"
onglet = "Janvier"
ChampAlire = "B2:B5"
LitChamp ChampOuCopier, Chemin, Fichier, onglet, ChampAlire
End Sub
Sub LitChamp(ChampOuCopier, Chemin, Fichier, onglet, ChampAlire)
Range(ChampOuCopier).FormulaArray = "='" & Chemin & "\[" & Fichier & "]" & onglet & "'!" & ChampAlire
Range(ChampOuCopier) = Range(ChampOuCopier).Value
End Sub
Rcupration du format des cellules pointes par des formules
Une feuille contient des formules du type
=Feuil2!C3
On veut que le format des cellules qui contiennent ces formules soit modifi lorsque le format des
cellules pointes est modifi. - RcupreFormats -
Private Sub Worksheet_Activate()
For Each c In ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas, 23)
tmp = c.Formula
If Not inclus(tmp, "[]*/+-") Then
a = Split(Mid(tmp, 2), "!")
If UBound(a) = 0 Then
Range(a(0)).Copy
Else
Sheets(a(0)).Range(a(1)).Copy
End If
c.PasteSpecial Paste:=xlPasteFormats
-
End If
Next c
End Sub
Function inclus(chaine, sch)
tmoin = False
For i = 1 To Len(sch)
If InStr(chaine, Mid(sch, i, 1)) > 0 Then tmoin = True
Next i
inclus = tmoin
End Function
Transforme BD en tableau
TransformeBDTableau
Transforme tableau en BD
Transforme Tableau BD
-
Sub TransformeLigneColonne()
Set f1 = Sheets("BD")
a = Sheets("Source").[B1].CurrentRegion
ligBD = 2
For ligne = 2 To UBound(a, 1)
For col = 2 To UBound(a, 2)
If a(ligne, col) > 0 Then
f1.Cells(ligBD, 1) = a(ligne, 1)
f1.Cells(ligBD, 2) = a(1, col)
f1.Cells(ligBD, 3) = a(ligne, col)
ligBD = ligBD + 1
End If
Next col
Next ligne
End Sub
Autre exemple
Transforme Tableau BD
Sub transformeTableauBD()
Set f = Sheets("bd")
a = f.[A1:D8]
ligne = 2: colonne = 6
For col = 2 To UBound(a, 2)
For lig = 2 To UBound(a)
f.Cells(ligne, colonne) = a(1, col)
f.Cells(ligne, colonne + 1) = a(lig, 1)
-
f.Cells(ligne, colonne + 2) = a(lig, col)
ligne = ligne + 1
Next lig
Next col
End Sub
Autre exemple
Sub TransformeTableauBD()
ligne = 2
For Each c In Range("A2:A" & [A65000].End(xlUp).Row)
For J = 1 To 3
Cells(ligne, 8) = c
Cells(ligne, 9) = c.Offset(, 1)
Cells(ligne, 10) = Val(c.Offset(, J + 1))
ligne = ligne + 1
Next
Next c
End Sub
Autre exemple
Sub Transforme()
ligne = 2
-
For Each c In Range("A2:A" & [A65000].End(xlUp).Row)
a = Split(c.Offset(, 1), "/")
For j = LBound(a) To UBound(a)
Sheets(2).Cells(ligne, 1) = c
Sheets(2).Cells(ligne, 2) = a(j)
ligne = ligne + 1
Next
Next c
End Sub
Transformation de BD en tableau
TransformeColonnesLignes
TransformeColonneLigneEnfants
Sub ColonneLigne()
Application.ScreenUpdating = False
LigneBD = 2
LigneResult = 2
Do While Cells(LigneBD, 1) ""
temp = Cells(LigneBD, 1)
Sheets("result").Cells(LigneResult, 1) = Cells(LigneBD, 1)
c = 2
Do While Cells(LigneBD, 1) = temp
Sheets("result").Cells(LigneResult, c) = Cells(LigneBD, 2)
c = c + 1
LigneBD = LigneBD + 1
Loop
LigneResult = LigneResult + 1
Loop
End Sub
Avec formules
-Slectionner A2 =SI(MIN(SI(Code"";SI(NB.SI(A$1:A1;Code)=0;LIGNE(INDIRECT("1:"&LIGNES(Code))))))0;
INDEX(Code;MIN(SI(Code"";SI(NB.SI(A$1:A1;Code)=0;LIGNE(INDIRECT("1:"&LIGNES(Code)))))));"")
-Valider avec Maj+Ctrl+entre
-
en B2:
=SI(COLONNES($B:B)
-
For j = f1.Cells(LigneSource, 1) To f1.Cells(LigneSource, 2)
f2.Cells(LigneDest, 1) = j
f2.Cells(LigneDest, 2) = f1.Cells(LigneSource, 3)
f2.Cells(LigneDest, 3) = f1.Cells(LigneSource, 4)
LigneDest = LigneDest + 1
Next
Next
End Sub
Autre exemple
Sub TransformeColooneLigne()
Application.ScreenUpdating = False
Range("A1").CurrentRegion.Sort Key1:=Range("A2"), Header:=xlYes
Range("a2").Select
ligne = 2
Do While ActiveCell ""
mmatricule = ActiveCell
Sheets("rsult").Cells(ligne, 1) = ActiveCell
Sheets("rsult").Cells(ligne, 2) = ActiveCell.Offset(0, 1)
c = 3
Do While ActiveCell = mmatricule
Sheets("rsult").Cells(ligne, c) = ActiveCell.Offset(0, 2)
Sheets("rsult").Cells(ligne, c + 1) = ActiveCell.Offset(0, 3)
c = c + 2
ActiveCell.Offset(1, 0).Select
Loop
ligne = ligne + 1
Loop
Range("a2").Select
End Sub
Transformation de colonnes en lignes avec 2 niveaux de rupture
-
ColonneLignes
Tableau convertir:
Ce que l'on veut obtenir
Sub TransformeColonneLigne()
Range("A1").CurrentRegion.Sort Key1:=Range("A2"), Key2:=Range("b2"), Key3:=Range("b3"),
Header:=xlYes
Range("a2").Select
ligne = 2
Do While ActiveCell ""
mIdCli = ActiveCell
Sheets("rsult").Cells(ligne, 1) = ActiveCell
c = 2
Do While ActiveCell = mIdCli
Sheets("rsult").Cells(ligne, c) = ActiveCell.Offset(0, 1)
Sheets("rsult").Cells(ligne, c + 1) = ActiveCell.Offset(0, 2)
c = c + 2
mRefContt = ActiveCell.Offset(0, 1)
Do While ActiveCell = mIdCli And ActiveCell.Offset(0, 1) = mRefContt
ActiveCell.Offset(1, 0).Select
Loop
Loop
ligne = ligne + 1
Loop
End Sub
-
Transformation colonne en ligne avec formule matricielle
Transforme colonnes en lignes
Transformation de fiches en BD
TransformeFicheBD
Sub transpose()
dbut = 2
fin = [A65000].End(xlUp).Row
pas = 5
Dim a()
ReDim a(1 To (fin) / pas, 1 To 4)
For i = dbut To fin Step pas
For k = 0 To 3: a((i + pas - dbut) / pas, k + 1) = Cells(i + k, 1): Next k
Next i
[C2].Resize((fin) / pas, 4) = a
End Sub
Sub transpose2()
dbut = 2
fin = [A65000].End(xlUp).Row
pas = 5
-
ligne = 2
For i = dbut To fin Step pas
For k = 0 To 3
Cells(ligne, 3 + k) = Cells(i + k, 1)
Next k
ligne = ligne + 1
Next i
End Sub
Trim Rapide
Sub TrimRapide()
t = Timer()
Columns("B:B").Insert Shift:=xlToRight
[B1:B12000].FormulaArray = "=TRIM(A1:A12000)"
[A1:A12000] = [B1:B12000].Value
Columns("B:B").Delete
MsgBox Timer() - t
End Sub
Slection 1 ligne sur 2 rapide
-La formule =SI(MOD(LIGNE();2)=1;"";1) dans la colonne B crit 1 dans une cellule sur 2
- [B2:B65000].SpecialCells(xlCellTypeFormulas, 1).Offset(0, -1).Select slectione les cellules contenant une
valeur.
Application.ScreenUpdating = False
Columns("b:b").Insert Shift:=xlToRight
[B2].FormulaR1C1 = "=IF(MOD(ROW(),2)=1,"""",1)"
[B2].AutoFill Destination:=Range("B2:B" & [A65000].End(xlUp).Row)
[B2:B65000].SpecialCells(xlCellTypeFormulas, 1).Offset(0, -1).Select
Columns("b:b").Delete Shift:=xlToLeft
-
Editeur de couleurs
Permet de modifier une couleur dans un champ - Editeur couleur -
Sub couleur()
On Error Resume Next
Set CelluleCoulAnc = Application.InputBox(prompt:=
"Cliquez sur la cellule contenant la couleur modifier", Type:=8)
If CelluleCoulAnc Is Nothing Then Exit Sub
On Error GoTo 0
anc = CelluleCoulAnc.Interior.ColorIndex
Range("A1").Select
retour = Application.Dialogs(xlDialogPatterns).Show
If retour = False Then Exit Sub
nouv = [A1].Interior.ColorIndex
Set champ = Application.InputBox(prompt:="Champ modifier", Type:=8)
For Each c In champ
If c.Interior.ColorIndex = anc Then c.Interior.ColorIndex = nouv
Next c
End Sub
Liste des feuilles d'un classeur contenant un mot cherch
- Cherche mot classeur -
Private Sub B_ok_Click()
If Me.TextBox1 = "" Then Exit Sub
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Temp").Delete
On Error GoTo 0
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = "Temp"
'--
ligne = 2
For Each s In ActiveWorkbook.Sheets
-
With Sheets(s.Name).Cells
Set c = .Find(Me.TextBox1, LookIn:=xlValues, LookAt:=xlWhole)
If Not c Is Nothing Then
Sheets("temp").Cells(ligne, 1) = s.Name
ligne = ligne + 1
End If
End With
Next s
End Sub
Lettre no de colonne
col = 28
y = Replace(Replace(Cells(1, col).Address, "$", ""), "1", "")
MsgBox y
Conversion adresses relatives en absolu
Sub convertFeuille()
On Error Resume Next
Set champ = Sheets(1).Cells.SpecialCells(xlCellTypeFormulas)
Set C = champ.Find(What:="[", LookIn:=xlFormulas, LookAt:=xlPart)
If Not C Is Nothing Then
premier = C.Address
Do
C.Formula = _
Application.ConvertFormula(C.Formula, fromReferenceStyle:=xlA1, toAbsolute:=xlAbsolute)
Set C = champ.FindNext(C)
Loop While Not C Is Nothing And C.Address premier
End If
End Sub
Reprer les doublons dans des champs multi-feuilles
DoublonsChampsMultiFeuilles
Sub ColoriageDoublons()
For Each t In Array("champ1", "champ2", "champ3")
For Each c In Range(t)
For Each z In Array("champ1", "champ2", "champ3")
For Each d In Range(z)
-
If c.Value = d.Value And c.Address d.Address Then
c.Interior.ColorIndex = 4
f = feuil(t)
temp = c.Address
On Error Resume Next
Sheets(f).Range(temp).Comment.Delete
Sheets(f).Range(temp).AddComment
Sheets(f).Range(temp).Comment.Text Text:=feuil(z) & Chr(10) & d.Address
Sheets(f).Range(temp).Comment.Shape.TextFrame.AutoSize = True
End If
Next d
Next z
Next c
Next t
End Sub
Function feuil(nom)
For Each n In ActiveWorkbook.Names
If n.Name = nom Then
a = Split(n, "!")
feuil = Mid(a(0), 2)
End If
Next n
End Function
Modification couleur de la slection
Modifie la couleur du champ slectionn l'intrieur du champ B2:E20 et restitue les anciennes couleurs.
SelectionModifieCouleur
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set champ = [B2:E20]
'---- restitution des couleurs
For Each n In ActiveWorkbook.Names
Range(Mid(n.Name, 12)).Interior.ColorIndex = Val(Mid(n, 2))
n.Delete
Next n
'--- mmorisation des couleurs --------------------------
If Not Intersect(champ, Target) Is Nothing And Target.Count
-
"=" & c.Interior.ColorIndex
c.Interior.ColorIndex = 6
Next c
End If
End Sub
Curseur ligne
Sans gestion des couleurs
En cliquant sur une cellule d'un champ, la ligne est surligne. Les anciennes couleurs ne sont pas rtablies
lorsque le curseur est dplac.
CurseurLigneSansCouleur
CurseurLigneSansCouleurMZ
CurseurLigneSansCouleurMZ3
jb-curseur
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set champ = Range("Lazone") ' ou Set champ = Range("B2:G12")
If Not Intersect(champ, Target) Is Nothing And Target.Count = 1 Then
champ.Interior.ColorIndex = xlNone
col1 = champ.Column
col2 = col1 + champ.Columns.Count - 1
Range(Cells(Target.Row, col1), Cells(Target.Row, col2)).Interior.ColorIndex = 36
End If
End Sub
Avec gestion des couleurs
En cliquant sur une cellule d'un champ, la ligne est surligne. Les anciennes couleurs sont rtablies lorsque le
curseur est dplac.
CurseurLigne
CurseurLigneMZ
-
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set champ = [B1:E20] ' ou Set champ = range("MaZone")
For Each n In ActiveWorkbook.Names
If n.Name = "mmoNcol" Then trouv = True
Next n
If trouv Then
'---- restitution des couleurs
ncol = [mmoNCol]
For i = 1 To ncol
x = "mmoAdresse" & i
a = Evaluate([x])
x = "mmoCouleur" & i
b = Evaluate([x])
Range(a).Interior.ColorIndex = b
Next i
End If
'--- mmorisation des couleurs -------------------------- If Not Intersect(champ, Target) Is Nothing And Target.Count = 1 Then
col1 = champ.Column
col2 = champ.Column + champ.Columns.Count - 1
ncol = col2 - col1 + 1
ActiveWorkbook.Names.Add Name:="mmoNcol", RefersToR1C1:= _
"=" & Chr(34) & ncol & Chr(34)
For i = 1 To ncol
ActiveWorkbook.Names.Add Name:="mmoAdresse" & i, RefersToR1C1:= _
"=" & Chr(34) & Cells(Target.Row, i + col1 - 1).Address & Chr(34)
ActiveWorkbook.Names.Add Name:="mmoCouleur" & i, RefersToR1C1:= _
"=" & Cells(Target.Row, i + col1 - 1).Interior.ColorIndex
Cells(Target.Row, i + col1 - 1).Interior.ColorIndex = 6
Next i
End If
End Sub
Curseur ligne/colonne
Curseur ligne/colonne. Les anciennes couleurs sont restitues.
CurseurLigneColonneAvecMFC
-
CurseurLigneChampAvecMFC
CurseurLigneColonneSansMFC
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set champ = Range("A1:M20")
If Me.CheckBox1 Then
If Not Intersect(champ, Target) Is Nothing Then
champ.FormatConditions.Delete
If Target.Count = 1 Then
Union(Intersect(Target.EntireRow, champ), Intersect(Target.EntireColumn,
champ)).FormatConditions.Add Type:=xlExpression, Formula1:="VRAI"
Union(Intersect(Target.EntireRow, champ),
Intersect(Target.EntireColumn, champ)).FormatConditions(1).Interior.ColorIndex = 36
End If
End If
Else
champ.FormatConditions.Delete
End If
End Sub
Mise en forme d'une BD
BDMiseForme
-
Private Sub Worksheet_Activate()
Sheets("feuil2").Select
[1:10000].Delete
Sheets("feuil1").[A1].CurrentRegion.Copy [A1]
[A1].CurrentRegion.Sort Key1:=Range("C2"), Order1:=xlAscending, Header:=xlGuess
i = 2
Do While Cells(i, 3) ""
temp = Cells(i, 3)
Rows(i).Insert
Cells(i, 1) = temp
Cells(i, 1).Resize(, 4).Interior.ColorIndex = 6
Cells(i, 1).Resize(, 4).Merge
Cells(i, 1).HorizontalAlignment = xlCenter
i = i + 1
Do While Cells(i, 3) = temp: i = i + 1: Loop
Loop
End Sub
Autre exemple
Mef
Private Sub Worksheet_Activate()
[1:10000].Delete
Sheets("BD").[A1].CurrentRegion.Copy [A1]
[A1].CurrentRegion.Sort Key1:=[A2], Order1:=xlAscending, Header:=xlGuess
i = 2
Do While Cells(i, 1) ""
temp = Left(Cells(i, 1), 1)
Rows(i).Insert
Cells(i, 1) = temp
Cells(i, 1).Font.Bold = True
Cells(i, 1).Resize(, 3).Interior.ColorIndex = 6
Cells(i, 1).Resize(, 3).Merge
i = i + 1
-
Do While Left(Cells(i, 1), 1) = temp: i = i + 1: Loop
Loop
End Sub
Rupture
Sub rupture()
Application.DisplayAlerts = False
On Error Resume Next
Sheets("BD2").Delete
On Error GoTo 0
Sheets("BD").Copy after:=Sheets(1)
ActiveSheet.Name = "BD2"
ligne = 2
Do While Cells(ligne, 1) ""
activit = Cells(ligne, 3)
Rows(ligne).Insert
Cells(ligne, 1) = activit
Cells(ligne, 1).Font.Bold = True
ligne = ligne + 1
Do While Cells(ligne, 3) = activit
ligne = ligne + 1
Loop
Loop
Columns(3).Delete
End Sub