Définir un champRange(champ)Range permet de spécifier un champ. Range("B3").Select Cells(ligne,Colonne) Cells(ligne,colonne) représente
la cellule qui est à l'intersection de ligne et de colonne. Cells(3,2).Select Range(champ).Cells(ligne,colonne)La ligne et la colonne sont relatives au début du champ spécifié dans Range Range("B3:D6").cells(1,1).select Cellule activeActiveCellLa cellule active se spécifie avec ActiveCell. Sur cet exemple, la variable X prend la valeur de la cellule active et va s’écrire en A1 x=ActiveCell.Value Positionner le curseurRange(champ).Select sélectionne le champ spécifié Range("B3").Select ' Sélectionne la cellule
B3 Déplacer le curseurActivecell.Offset(nb_lignes,nb_colonnes).SelectActivecell.Offset(nb_lignes,nb_colonnes).Select déplace le curseur du nombre de lignes et de colonnes spécifiés. Range("A1").Select 'Se
positionne en A1 Masquer la mise à jour de l'écranApplication.ScreenUpDating=True/FalseApplication.ScreenUpdating=False désactive
la mise à jour de l'écran. Application.ScreenUpdating=False Champ.End(xlDown-XlUp-XlToRight-XlToLeft) champ.End(XlDown) représente: Range("A1").End(xlDown).Select
' positionne sur A4 champ.End(XlUp) représente: Range("A7").End(xlUp).Select '
sélectionne A4 champ.End(XlToRight) et champ.End(XlToLeftt)
correspondent à un déplacement Range("A1").End(xlToRight).Select ' sélectionne D1 Sélectionner la région couranteCurrentRegionchamp.CurrentRegion sélectionne les cellules autour du champ spécifié. Range("A1").CurrentRegion.Select
' sélectionne
les cellules autour de A1 Range("A1").currentregion.Select Range("A1").CurrentRegion.PrintPreview ' Aperçu Rédéfinir la taille d'un champResize(lignes,colonnes)Redéfinit la taille d'un champ. Range("A1").Resize(1,4).Select ' sélectionne A1:D1 Range("A1").CurrentRegion.Select Sélectionner les cellules particulièresChamp.SpecialCells(type,valeur) -SpecialCells permet de sélectionner
des cellules particulières. C'est l'équivalent
-Si type a la valeur xlCellTypeConstants ou xlCellTypeFormulas, valeur spécifie le type de cellules: nombre, texte,valeurs logiques, erreurs. Cells.SpecialCells(xlLastCell).Select '
Sélectionne la dernière cellule de la feuille Supprimer les lignes vides en colonne A On Error Resume Next 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 déverrouilléesSub raz() Tri d'un champ lignes/colonnesSub TriTab2D() Sélectionner la zone utilisée d'une feuilleUsedRangeSélectionne la zone utilisée dans la feuille active. ActiveSheet.UsedRange.Select MsgBox ActiveSheet.UsedRange.Address Sélection de la dernière cellule Range(Split(ActiveSheet.UsedRange.Address, ":")(1)).Select Union et Intersection de champsUnion(champ1,Champ2,…)Donne l'union de champ1,champ2,... Union([A2:B2], [A4:B4]).Select Copie des cellules pleines de plusieurs champs dans un seul champLes cellules sont dans la même colonne: Range("A1:A5,A10:A15").SpecialCells(xlCellTypeConstants, 23).Copy [D2] Les cellules ne sont pas dans la même colonne: i = 1 Sélectionne les cellules non verrouilléesSub SelectNonVer() Sub auto_open() Ajout de listes
Définition d'un champ discontinu dynamiqueOn veut définir le champ B2:B5,D2:D5,F2:F5 de façon dynamique(on ne sait pas combien il y aura de colonnes) A B C D E F Private Sub Worksheet_Change(ByVal Target As Range) Autre exemple: on prend 1 colonne sur 2 Sub UnionDynamique() 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 informationFind()Champ.Find(What:=valeur,
After:=cellule, LookIn:=xlFormulas/XlValues, Recherche un texte dans une champ. Find correspond à la commande Edition/Rechercher. LookAt:= xlPart/XlWhole définit
si la comparaison se fait sur une partie ou la totalité de la cellule. LookIn:=xlFormulas/XlValues spécifie si la recherche se fait dans la formule ou le résultat. Par défaut, ce paramètre conserve la valeur précédente. Exemple : On cherche un nom Méthode 1 (gestion d'erreur) Sub cherche() Méthode 2 Sub cherche2() Donne toutes les occurrences : Sub cherche_plusieurs() Non concordanceColorie les objets de la colonne A non trouvés dans D2:D5. Sub coloriage() Recherche de la dernière ligne ou dernière colonne de la feuille ou d'un champSur cet exemple, nous recherchons la dernière ligne et la dernière colonne de la feuille. Sub dernièreligneFeuille() Nombre de lignes et de colonnes de la feuille. Sub nbLignesFeuille() Sur cet exemple, nous recherchons la dernière ligne et la dernière colonne d'un champ. Sub dernièreligneChamp() Sélectionne de la ligne1 à la dernière ligne des colonnes D :E x = "D:E" Recherche de la première ligne vide dans un champRecherche la première ligne vide dans le champ A2:A1000 1 Nom Sub ChercheLigneVide() Recherche de dateLe format de la date cherchée est le même que le format des dates du champ de rechercheSub RechercheDateFind() On adapte le format de la date recherchée au format des dates du champ de rechercheSub RechercheDateFind2() Avec la fonction Equiv(), le format des dates du champ de recherche n'a pas d'importanceSub RechercheDateColonneEquiv() Remplace les abréviations sélectionnées par les libellésSub traduc() ou Sub traduc2() Recherche de nombres avec Find ValCherchée = InputBox("Valeur recherchée") Colorie les occurences du mot cherché dans un champColorie les occurences du mot cherché dans un champPrivate Sub Worksheet_Change(ByVal Target As Range) Nettoyage d'une feuilleParfois, le UsedRange d'une feuille (Maj+Ctrl+fin)
comporte des lignes et des colonnes après la dernière cellule
pleine. Sub SupLigneColTrop() Sub VisuUsedRange() Recherche 2 critèresRecherche matricielle 2 critèresOn suppose que le nom cherché est en F2 et le prénom
en G2 . Nom et Prenom sont 2 champs
nommés. Sub Recherche() Le nom et le prénom sont dans des variables n et P. Sub Recherche2() Recherche 2 critères dans un tableauSub RechercheMultiCritères() Recherche 2 critères avec findSub FindMultiCritères() Recherche Find avec caractères accentuésCréation d'une BD à partir de fichesOn recherche la position du mot prénom
dans les cellules. Prénom est écrit avec
ou sans accent. Sub CréeBD() 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 ? valeurCherchéeJoker = "?tudiant" Find Accent
(0,04 s pour 25.000 lignes) Sub FindAccent() Avec une recherche séquentielle (0,75s pour 25.000 lignes) Sub RechSeqAccent() Recherche d'un mot dans une BDLa recherche se fait dans toutes les colonnes de la BD. Le filtrage est obtenu en masquant les lignes. On peut placer le curseur sur une ligne en cliquant dans la ListBox. Private Sub B_ok_Click() Recherche d'un mot dans tout le classeurDonne la liste des feuilles d'un classeur contenant le mot cherché. Recherche mot dans tout le classeur Private Sub B_ok_Click() Supprimer les lignes videsCellules vides dans la colonne A On Error Resume Next Cellules vides sur toutes les colonnes For i = [A65000].End(xlUp).Row To 1 Step -1 Cellules vides de la colonne B à la colonne HSub suplignesvides() Sub supLignesVides2() Suppression des lignes et colonnes vides For i = ActiveSheet.UsedRange.Rows.Count To 1 Step -1 Sélection de lignesOn veut sélectionner les lignes des années 2008. Sub Selection2008() Suppression de lignesSuppression classiqueOn supprime les lignes qui contiennent xxxx dans la première colonne Application.ScreenUpdating = False ou [A:A].Replace "xxxx", "" Avec le filtre automatiqueSupLignesFiltreAuto Sub SupLignesFiltreAuto() Avec le filtre élaboréSupprime les exclus - xx yy zz - ( 0,1 S pour 10.000 lignes). Sub sup_filtre() A l'aide d'une colonne intermédiaire:Sub supLignes() On regroupe les lignes à supprimer en fin de tableau. -on repère les lignes à supprimer avec la
valeur Sup (0,2sec pour 20.000 lignes) SupLignesRapide Sub supLignesRapide() Autre méthode (0,15 sec pour 20.000 lignes) Sub supLignesRapide2() Suppression de lignes rapide d'un tableau structuréSup Lignes d'un tableau structuré
Suppression classique de lignes n'appartenant pas à une listeSub supLignesListeClassique() Sub supLignesListeRapide() Supprimer des lignes commençant parSub SupLignes3() Suppression de lignes sur 3 colonnes For i = [A65000].End(xlUp).Row To 1 Step -1 Suppression de cellules vides[A:D].SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp Supprime une ligne sur 2 (rapide)Sub supLignes1sur2() Sub supLignes1sur2Rapide() Masquage de lignesOn masque les lignes si cellules vides dans colonne B On Error Resume Next On masque les lignes si cellules vides dans toutes les colonnes For i = 1 To [A65000].End(xlUp).Row Pour faire apparaître 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 Insère une ligne vide entre les lignes Range("A65000").End(xlUp).Select Suppression de doublonsSub supDoublonsTradi() Suppression de doublons rapideLorsque le nombre de lignes devient important et si le
taux de suppression est élevé, la méthode ci dessous Sub SupRapide1Critere() Sub SupRapide2CriteresColAColB() Suppression de doublons sans modifier l'ordreSur colonne ASub supdoublons() Sur colonne A et CRapide si taux de suppression faible. 2 s pour 10.0000 lignes et taux suppression 5% Sub OrdreRespectéDictionary() Complèter un champ [A1:A20].SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C" Autre cas [A1].CurrentRegion.Resize(, 1).SpecialCells(xlCellTypeBlanks).FormulaR1C1
= "=R[-1]C" Insère une ligne à la position du curseur et copie les formulesSub InsèreCopieLigne() Recopie la dernière ligne et ne laisse que les formulesSub RecopieDerniereLigne() Pour affecter une macro au clic droit sur cette feuille :Private Sub Worksheet_Activate() Private Sub Worksheet_Deactivate() Remplacer une informationReplace() Champ.Replace What:=valeur, Replacement:=valeur, Remplace une chaîne de caractères par une autre chaîne. Range(“A1:A10”).Replace " ", "" Caractères spéciaux:* : remplace un nombre indéderminé
de caractères S'il y a un caractère spécial dans la chaîne, utiliser ~ devant le caractère spécial: Sur cet exemple, on remplace le caractère * par une chaîne vide aaa*aaa Range(“A1:A10”).Replace "~* ", "" Supprime les lignes se terminant par DE mmm [A:A].Replace What:="*DE", Replacement:="",
LookAt:=xlWhole Remplacer VRAI/FAUXPour remplacer les valeurs booléennes VRAI et FAUX dans une feuille Cells.Replace What:=True, Replacement:="x" Positionnement du curseur ScrollRow=ligne
|
|
|
Avant |
Après |
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 fusionnée
If [B5].MergeCells Then MsgBox [B5].MergeArea.Address
La fonction RechercheMZ(valCherchée, champRech As Range, ChampRetour) donne une valeur associée à une valeur cherchée
=RechercheMZ(K2;(A2:A7;D2:D5;G2:G7);(B2:B7;E2:E5;H2:H7))
Si les champs ont étés nommés:
=RechercheMZ(K2;Noms;Salaire)
Function RechercheMZ(valCherchée, champRech As Range,
ChampRetour)
Application.Volatile
For i = 1 To champRech.Areas.Count
For j = 1 To champRech.Areas(i).Count
If valCherchée = champRech.Areas(i)(j)
Then
RechercheMZ = ChampRetour.Areas(i)(j)
Exit Function
End If
Next j
Next i
RechercheMZ = "pas trouvé"
End Function
Sélectionner le champ puis exécuter la macro.
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
Sub glissant()
'-- décalage des 11 derniers mois sur le premier
Range("C1:M7").Cut Destination:=Range("B1")
'--- recopie la dernière 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
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
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
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
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
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
On veut connaître 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
Sur cet exemple, nous transférons les BD dans des tableaux tnom(),tprenom(),tage() pouraccélérer 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)
témoin = 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 témoin = True
Next k
If Not témoin 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
Récupère 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
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 pointées est modifié.
RécupèreFormats
RécupèreFormatsCommentaires
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)
témoin = False
For i = 1 To Len(sch)
If InStr(chaine, Mid(sch, i, 1)) >
0 Then témoin = True
Next i
inclus = témoin
End Function
Coloriage
antécédents
Evaluation expression
Transforme
Tableau BD
Transforme Tableau BD2
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
Sub TransformeBD2()
a = Sheets("Feuil1").Range("A1:D" &
[A65000].End(xlUp).Row)
Dim b()
ReDim b(1 To UBound(a) * 2, 1 To UBound(a, 2))
Set f1 = Sheets("feuil1")
ligBD = 1
colBD = 1
For ligne = 2 To UBound(a, 1)
For col = 3 To UBound(a, 2)
b(ligBD, colBD) = a(ligne, 1)
b(ligBD, colBD + 1) = a(ligne, 2)
b(ligBD, colBD + 2) = a(1, col)
b(ligBD, colBD + 3) = a(ligne, col)
ligBD = ligBD + 1
Next col
Next ligne
f1.[H2].Resize(UBound(b), UBound(b, 2)) = b
End Sub
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
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
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
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
-Sélectionner 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+entrée
en B2:
=SI(COLONNES($B:B)<=NB.SI(Code;$A2);INDEX(val;EQUIV($A2;Code;0)+COLONNES($B:B)-1;1);"")
Autre exemple
Sub ColonneLigne()
LigneDest = 2
For LigneSource = 2 To [A65000].End(xlUp).Row
For j = 1 To Cells(LigneSource, 1)
Cells(LigneDest, 5) = Cells(LigneSource,
2)
Cells(LigneDest, 6) = Cells(LigneSource,
3)
LigneDest = LigneDest + 1
Next
Next
End Sub
Autre exemple
Sub ColonneLigne()
Set f1 = Sheets("Données initiales")
Set f2 = Sheets("Format final")
LigneDest = 2
For LigneSource = 2 To f1.[A65000].End(xlUp).Row
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("résult").Cells(ligne,
1) = ActiveCell
Sheets("résult").Cells(ligne,
2) = ActiveCell.Offset(0, 1)
c = 3
Do While ActiveCell = mmatricule
Sheets("résult").Cells(ligne,
c) = ActiveCell.Offset(0, 2)
Sheets("résult").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
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("résult").Cells(ligne,
1) = ActiveCell
c = 2
Do While ActiveCell = mIdCli
Sheets("résult").Cells(ligne,
c) = ActiveCell.Offset(0, 1)
Sheets("résult").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
TransformeFicheBD
TransformeFicheBD2
Sub transpose()
début = 2
fin = [A65000].End(xlUp).Row
pas = 5
Dim a()
ReDim a(1 To (fin) / pas, 1 To 4)
For i = début To fin Step pas
For k = 0 To 3: a((i + pas - début) / pas,
k + 1) = Cells(i + k, 1): Next k
Next i
[C2].Resize((fin) / pas, 4) = a
End Sub
Sub transpose2()
début = 2
fin = [A65000].End(xlUp).Row
pas = 5
ligne = 2
For i = début 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
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
-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
sélectione 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
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
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
col = 28
y = Replace(Replace(Cells(1, col).Address, "$", ""),
"1", "")
MsgBox y
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
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
Modifie la couleur du champ sélectionné à l'intérieur du champ B2:E20 et restitue les anciennes couleurs.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set champ = Range("A1:D20")
'---- restitution couleurs
If Not Intersect(champ, Target) Is Nothing And Target.Count
< 100 Then
CoulCurseur = RGB(255, 255, 0)
For Each n In ActiveWorkbook.Names
If Left(n.Name, 7) = "MémoAdr"
Then
adr = Mid(n.Name, 8):
Coul = Val(Mid(n, 2)): If Coul = 16777215 Then Coul = xlNone
If Range(adr).Interior.Color
= CoulCurseur Then Range(adr).Interior.Color = Coul
End If
Next n
'------ sauvegarde couleurs
For Each n In ActiveWorkbook.Names
If Left(n.Name, 7) = "MémoAdr"
Then n.Delete
Next n
For Each c In Target
ActiveWorkbook.Names.Add Name:="MémoAdr"
& Replace(c.Address, "$", ""), RefersTo:=c.Interior.Color
Next c
Target.Interior.Color = CoulCurseur
End If
End Sub
En cliquant sur une cellule d'un champ, la ligne est surlignée.
Les anciennes couleurs ne sont pas rétablies
lorsque le curseur est déplacé.
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
En cliquant sur une cellule d'un champ, la ligne est surlignée. Les anciennes couleurs sont rétablies lorsque le curseur est déplacé.
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 = "mémoNcol"
Then trouvé = True
Next n
If trouvé Then
'---- restitution des couleurs
ncol = [mémoNCol]
For i = 1 To ncol
x = "mémoAdresse" &
i
a = Evaluate([x])
x = "mémoCouleur" &
i
b = Evaluate([x])
Range(a).Interior.ColorIndex = b
Next i
End If
'--- mémorisation 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:="mémoNcol",
RefersToR1C1:= _
"=" & Chr(34) & ncol & Chr(34)
For i = 1 To ncol
ActiveWorkbook.Names.Add Name:="mémoAdresse"
& i, RefersToR1C1:= _
"=" & Chr(34)
& Cells(Target.Row, i + col1 - 1).Address & Chr(34)
ActiveWorkbook.Names.Add Name:="mémoCouleur"
& 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. Les anciennes couleurs sont restituées.
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
Remplace le curseur de la cellule active par un curseur rouge. On peut aussi choisir une forme ovale.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
ActiveSheet.Shapes("Curseur").Visible = True
If Err <> 0 Then
ActiveSheet.Shapes.AddShape(msoShapeRectangle,
6, 6, 8, 6).Name = "curseur"
ActiveSheet.Shapes("Curseur").Fill.Transparency
= 1
ActiveSheet.Shapes("curseur").Line.Visible
= True
ActiveSheet.Shapes("curseur").Line.ForeColor.SchemeColor
= 10
ActiveSheet.Shapes("curseur").Line.Weight
= 3
End If
ActiveSheet.Shapes("curseur").Left = Target.Left
ActiveSheet.Shapes("curseur").Top = Target.Top
ActiveSheet.Shapes("curseur").Height = ActiveCell.Height
ActiveSheet.Shapes("curseur").Width = ActiveCell.Width
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect([a2:a13], Target) Is Nothing Then
[A1:J13].Interior.ColorIndex = xlNone
ligne = Target.Row
If Cells(ligne, "k").End(xlToLeft).Column
= 1 Then Exit Sub
Set horiz = Range(Cells(ligne, "a"),
Cells(ligne, "k").End(xlToLeft))
horiz.Interior.ColorIndex = 6
For Each c In horiz
If c = "x" Then
Range(c, Cells(1, c.Column)).Interior.ColorIndex = 6
Next c
End If
Colorie dernière cellule modifiée
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count = 1 Then
On Error Resume Next
If [mémoAdresse] <> ""
Then Range([mémoAdresse]).Interior.Color = [mémoCouleur]
On Error GoTo 0
ActiveWorkbook.Names.Add Name:="mémoAdresse",
RefersToR1C1:="=" & Chr(34) & Target.Address & Chr(34)
ActiveWorkbook.Names.Add Name:="mémoCouleur",
RefersToR1C1:="=" & Target.Interior.Color
Target.Interior.Color = RGB(255, 0, 0)
End If
End Sub
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
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
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
Sub Transforme()
Set f1 = Sheets("BD")
Set f2 = Sheets("Résult")
ligneBD = 2
finBD = f1.[B65000].End(xlUp).Row
LigneResult = 2
Do While ligneBD <= finBD
marque = f1.Cells(ligneBD, 1)
Do While (f1.Cells(ligneBD, 1) = marque
Or f1.Cells(ligneBD, 1) = "") And ligneBD <= finBD
ref = f1.Cells(ligneBD, 2)
f2.Cells(LigneResult, 1) = f1.Cells(ligneBD,
1)
numeros = f1.Cells(ligneBD,
3)
a = Split(numeros, "/")
For i = LBound(a) To UBound(a)
f2.Cells(LigneResult,
2) = ref
f2.Cells(LigneResult,
3) = Trim(a(i))
LigneResult = LigneResult
+ 1
Next i
ligneBD = ligneBD + 1
Loop
Loop
End Sub
Sub MajBD()
Set f1 = Sheets("BD")
Set f2 = Sheets("modif")
For Each c In f2.Range("a2:a" & f2.[a65000].End(xlUp).Row)
p = Application.Match(c, f1.Range("a2:a"
& f1.[a65000].End(xlUp).Row), 0)
If Not IsError(p) Then c.Resize(, 5).Copy f1.Cells(p
+ 1, 1)
Next c
End Sub
13 12 78
14 12 52
15 51 13
781 12 15
Sub Sup50()
seuil = 50
For Each c In Range("A2:A" & [A65000].End(xlUp).Row)
a = Split(c, " ")
For i = LBound(a) To UBound(a)
If Val(a(i)) > seuil Then
p = InStr(c, a(i))
If p > 0 Then
c.Characters(Start:=p,
Length:=Len(a(i))).Font.Bold = True
c.Characters(Start:=p,
Length:=Len(a(i))).Font.ColorIndex = 3
End If
End If
Next i
Next c
End Sub