Passer au contenu principal

Comment garder le tableau extensible en insérant une ligne de tableau dans une feuille de calcul protégée dans Excel?

La fonction d'expansion automatique du tableau sera perdue après la protection de la feuille de calcul dans Excel. Par exemple, il existe une table nommée Table1 dans votre feuille de calcul protégée, lorsque vous tapez quelque chose sous la dernière ligne, la table ne se développe pas automatiquement pour inclure la nouvelle ligne. Existe-t-il une méthode pour garder le tableau extensible en insérant une nouvelle ligne dans une feuille de calcul protégée? La méthode décrite dans cet article peut vous aider à y parvenir.

Gardez le tableau extensible en insérant une ligne de tableau dans une feuille de calcul protégée avec le code VBA


Gardez le tableau extensible en insérant une ligne de tableau dans une feuille de calcul protégée avec le code VBA

Comme illustré ci-dessous, une table nommée Table1 dans votre feuille de calcul et la dernière colonne de la table est une colonne de formule. Vous devez maintenant protéger la feuille de calcul pour éviter que la colonne de formule ne change, mais permettre d'agrandir le tableau en insérant une nouvelle ligne et en attribuant de nouvelles données dans les nouvelles cellules. Veuillez faire comme suit.

1. Cliquez Développeur > insérer > Bouton (contrôle de formulaire) pour insérer un Contrôle de formulaire bouton dans votre feuille de calcul.

2. Dans le pop-up Attribuer une macro boîte de dialogue, cliquez sur le Nouveauté .

3. dans le Microsoft Visual Basic pour applications , veuillez copier et coller le code VBA ci-dessous entre le Sol et End Sub paragraphes dans le Code fenêtre.

Code VBA: gardez le tableau extensible en insérant une ligne de tableau dans une feuille de calcul protégée

 'Update by ExtendOffice 20220826
    Dim xRg, tableRg As Range
    Dim xRowCount As Integer
    Dim pswStr As String
    pswStr = "123"
    On Error Resume Next
    Application.ScreenUpdating = False
    ActiveSheet.Unprotect Password:=pswStr

    Set tableRg = ActiveSheet.ListObjects("Table4").Range
    xRowCount = tableRg.Rows.Count
    
    Set xRg = Range("Table4[[#Headers],[Total]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault

    ActiveSheet.Protect Password:=pswStr, DrawingObjects:=False, _
                    Contents:=True, Scenarios:=False, _
                    AllowFormattingCells:=True, AllowFormattingColumns:=True, _
                    AllowFormattingRows:=True, AllowInsertingColumns:=True, _
                    AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, _
                    AllowDeletingColumns:=True, AllowDeletingRows:=True, _
                    AllowSorting:=True, AllowFiltering:=True, _
                    AllowUsingPivotTables:=True
    Application.ScreenUpdating = True

Notes:

1). Dans le code, le numéro «123» est le mot de passe que vous utiliserez pour protéger la feuille de calcul.
2). Veuillez modifier le nom de la table et le nom de la colonne contenant la formule que vous protégerez.

4. appuie sur le autre + Q touches pour fermer la fenêtre Microsoft Visual Basic pour Applications.

5. Sélectionnez les cellules du tableau dans lesquelles vous devez affecter de nouvelles données, à l'exception de la colonne de formule, puis appuyez sur le bouton Ctrl + 1 clés pour ouvrir le Format de cellule boite de dialogue. dans le Format de cellule boîte de dialogue, décochez la case Fermé , puis cliquez sur le OK bouton. Voir la capture d'écran:

6. Protégez maintenant votre feuille de calcul avec le mot de passe que vous avez spécifié dans le code VBA.

À partir de maintenant, après avoir cliqué sur le bouton Contrôle de formulaire dans votre feuille de calcul protégée, le tableau sera extensible en insérant une nouvelle ligne comme illustré ci-dessous.

Notes: vous pouvez modifier le tableau sauf la colonne de formule dans la feuille de calcul protégée.


Articles connexes:

Meilleurs outils de productivité bureautique

🤖 Aide à l'IA Kutools: Révolutionner l'analyse des données en s'appuyant sur : Exécution intelligente   |  Générer du code  |  Créer des formules personnalisées  |  Analyser les données et générer des graphiques  |  Invoquer les fonctions Kutools...
Caractéristiques populaires: Rechercher, mettre en évidence ou identifier les doublons   |  Supprimer les lignes vides   |  Combinez des colonnes ou des cellules sans perdre de données   |   Tour sans formule 
Super recherche: VSearchup à critères multiples    VSearch à valeurs multiples  |   Recherche virtuelle sur plusieurs feuilles   |   Recherche floue ....
Liste déroulante avancée: Créez rapidement une liste déroulante   |  Liste déroulante dépendante   |  Liste déroulante à sélection multiple ....
Gestionnaire de colonnes: Ajouter un nombre spécifique de colonnes  |  Déplacer les colonnes  |  Basculer l'état de visibilité des colonnes masquées  |  Comparer les plages et les colonnes 
Caractéristiques en vedette: Mise au point de la grille   |  Voir Design   |   Grande barre de formule    Gestionnaire de classeurs et de feuilles   |  Centre de ressources (Texte automatique)   |  Sélecteur de date   |  Combiner des feuilles de travail   |  Crypter/déchiffrer les cellules    Envoyer des e-mails par liste   |  Super filtre   |   Filtre spécial (filtre gras/italique/barré...) ...
Les 15 meilleurs ensembles d'outils12 Texte Outils (Ajouter du texte, Supprimer les caractères, ...)   |   50+ Graphique Types (Diagramme de Gantt, ...)   |   40+ Pratique Formules (Calculer l'âge en fonction de l'anniversaire, ...)   |   19 Insertion Outils (Insérer le code QR, Insérer une image à partir du chemin, ...)   |   12 Conversion Outils (Nombres en mots, Conversion des devises, ...)   |   7 Fusionner et fractionner Outils (Lignes de combinaison avancées, Cellules divisés, ...)   |   ... et plus

Améliorez vos compétences Excel avec Kutools for Excel et faites l'expérience d'une efficacité comme jamais auparavant. Kutools for Excel offre plus de 300 fonctionnalités avancées pour augmenter la productivité et gagner du temps.  Cliquez ici pour obtenir la fonctionnalité dont vous avez le plus besoin...

Description


Office Tab apporte une interface à onglets à Office et facilite grandement votre travail

  • Activer l'édition et la lecture par onglets dans Word, Excel, PowerPoint, Publisher, Access, Visio et Project.
  • Ouvrez et créez plusieurs documents dans de nouveaux onglets de la même fenêtre, plutôt que dans de nouvelles fenêtres.
  • Augmente votre productivité de 50% et réduit des centaines de clics de souris chaque jour!
Comments (19)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
hello, I've copied and pasted the code into VBA, amended the table name and selected the columns I want to protect. I click the button however all it does is protects the sheet but not add any new table rows. Any advice?
This comment was minimized by the moderator on the site
Sub ButtonOut_Click()

Dim PswS As String
PswStr = "54321"

On Error Resume Next

Application.ScreenUpdating = False
ActiveSheet.Unprotect Password:=PswStr

ActiveSheet.ListObjects("Table1").ListRows.Add

ActiveSheet.Protect Password:=PswStr
Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
The code is not working.
Several errors.

Dim xRg, tableRg As Range

xRg
is a variant not a range

yRg
not declared at all

Set xRg = Range("Table4[[#Headers],[Total]]").Offset(1, 0)

runtime error 1004
When I take away the TOTAL, it works.
It is not working with the total row displayed and neither when I hide the total row in the ribbon.

Normally your website is really great, but this article need improvment.
This comment was minimized by the moderator on the site
Hi prem,
You need to make sure that the table name and column header specified in the code match the table name and column header in the worksheet. To avoid the 1004 error, you may need to enable the trust access to the VBA project object model in your Excel: click File > Options > Trust Center > Trust Center Settings > Macro Settings > and then check the Trust access to the VBA project object model box.
This comment was minimized by the moderator on the site
Hi.

Thanks for sharing. Though I have a question... by using the code above, I can add one row at a time. How to add multiple rows in one click?

Thanks in advance.

'Update by ExtendOffice 20220826
Dim xRg, tableRg As Range
Dim xRowCount As Integer
Dim pswStr As String
pswStr = "123"
On Error Resume Next
Application.ScreenUpdating = False
ActiveSheet.Unprotect Password:=pswStr

Set tableRg = ActiveSheet.ListObjects("Table4").Range
xRowCount = tableRg.Rows.Count

Set xRg = Range("Table4[[#Headers],[Total]]").Offset(1, 0)
Set yRg = xRg.Resize(xRowCount, 1)
xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault

ActiveSheet.Protect Password:=pswStr, DrawingObjects:=False, _
Contents:=True, Scenarios:=False, _
AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowInsertingColumns:=True, _
AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, _
AllowDeletingColumns:=True, AllowDeletingRows:=True, _
AllowSorting:=True, AllowFiltering:=True, _
AllowUsingPivotTables:=True
Application.ScreenUpdating = True
This comment was minimized by the moderator on the site
Hola!!!
Tengo una tabla donde más de una columna está protegida.
La tabla tiene 17 columnas de las cuales 7 deben quedar bloqueadas porque poseen fórmulas.
Mi tabla arranca en celda A4

Estaba tratando de usar este código para probarlo, cambiando lo que verán abajo como "CLAVE", "MITABLA" y "AVISO 1" por mis nombres particulares:
Donde "AVISO 1" corresponde a una de las columnas que está protegida.

Dim pswStr As String
'Update by ExtendOffice 20181106
pswStr = "CLAVE"
On Error Resume Next
Application.ScreenUpdating = False
ActiveSheet.Unprotect Password:=pswStr
ActiveSheet.Range("A4").Select
Range("MITABLA[[#Headers],[AVISO 1]]").Select
Selection.End(xlDown).Select
Selection.Offset(1, -16).Select
ActiveCell.FormulaR1C1 = "new"
ActiveSheet.Protect Password:=pswStr, DrawingObjects:=False, _
Contents:=True, Scenarios:=False, _
AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowInsertingColumns:=True, _
AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, _
AllowDeletingColumns:=True, AllowDeletingRows:=True, _
AllowSorting:=True, AllowFiltering:=True, _
AllowUsingPivotTables:=True
Selection.ClearContents
Application.ScreenUpdating = True

Lo que está haciendo el código tal cual como lo escribo es que en lugar de agregar una nueva línea a mi tabla, está colocando la palabra "new" en la última celda con contenido de la columna "AVISO 1".

Surgen entonces 2 dudas:
1. ¿cómo podría hacer para determinar más de una columna protegida?
2. ¿por qué está haciendo esto el código definido?

Agradezco de antemano que me puedan ayudar! Estaré atenta.
This comment was minimized by the moderator on the site
Hi Daina,
1. If the 7 formula columns that you want to protect are consecutive in the table.
For example, the headers of the columns are gg, hh, ii, jj, kk, ll, mm as shown in the screenshot below. You can apply the following VBA code to get it done.
https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/table.png
In this line Set xRg = Range("Table3[[#Headers],[gg]:[mm]]").Offset(1, 0) in the following code, you just need to enter the headers of the first column and the last column.
Sub Button1_Click()
 'Update by ExtendOffice 20220826
    Dim xRg, tableRg As Range
    Dim xRowCount As Integer
    Dim pswStr As String
    pswStr = "123"
    On Error Resume Next
    Application.ScreenUpdating = False
    ActiveSheet.Unprotect Password:=pswStr

    'Change the table name and the column headers
    Set tableRg = ActiveSheet.ListObjects("Table3").Range
    xRowCount = tableRg.Rows.Count
    
     Set xRg = Range("Table3[[#Headers],[gg]:[mm]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, xRg.Columns.Count)

    xRg.Resize(xRowCount - 1, xRg.Columns.Count).AutoFill Destination:=yRg, Type:=xlFillDefault
    

    ActiveSheet.Protect Password:=pswStr, DrawingObjects:=False, _
                    Contents:=True, Scenarios:=False, _
                    AllowFormattingCells:=True, AllowFormattingColumns:=True, _
                    AllowFormattingRows:=True, AllowInsertingColumns:=True, _
                    AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, _
                    AllowDeletingColumns:=True, AllowDeletingRows:=True, _
                    AllowSorting:=True, AllowFiltering:=True, _
                    AllowUsingPivotTables:=True
    Application.ScreenUpdating = True
End Sub

2. If the 7 formula columns that you want to protect are discontinuous in the table. Apply the following code. In the code, you need to manually input the headers of the columns one by one.
Sub Button1_Click()
 'Update by ExtendOffice 20220826
    Dim xRg, tableRg As Range
    Dim xRowCount As Integer
    Dim pswStr As String
    pswStr = "123"
    On Error Resume Next
    Application.ScreenUpdating = False
    ActiveSheet.Unprotect Password:=pswStr

    'Change the table name and the column headers
    Set tableRg = ActiveSheet.ListObjects("Table3").Range
    xRowCount = tableRg.Rows.Count
    
    Set xRg = Range("Table3[[#Headers],[gg]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault
    Set xRg = Range("Table3[[#Headers],[hh]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault
    Set xRg = Range("Table3[[#Headers],[ii]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault
    Set xRg = Range("Table3[[#Headers],[jj]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault
    Set xRg = Range("Table3[[#Headers],[kk]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault
     Set xRg = Range("Table3[[#Headers],[ll]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault
    Set xRg = Range("Table3[[#Headers],[mm]]").Offset(1, 0)
    Set yRg = xRg.Resize(xRowCount, 1)
    xRg.Resize(xRowCount - 1, 1).AutoFill Destination:=yRg, Type:=xlFillDefault

    ActiveSheet.Protect Password:=pswStr, DrawingObjects:=False, _
                    Contents:=True, Scenarios:=False, _
                    AllowFormattingCells:=True, AllowFormattingColumns:=True, _
                    AllowFormattingRows:=True, AllowInsertingColumns:=True, _
                    AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, _
                    AllowDeletingColumns:=True, AllowDeletingRows:=True, _
                    AllowSorting:=True, AllowFiltering:=True, _
                    AllowUsingPivotTables:=True
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
How do I create a button to erase lines?
This comment was minimized by the moderator on the site
Merhaba Tablo ismini ve satır başlangıc yerlerini değiştirdiğim zaman kod çalışmıyor yardımcı olurmusunuz
This comment was minimized by the moderator on the site
Hi,
Make sure you have changed to the exact same table name and column header in the code.
I have changed the table name and the column header to test the code, and it works well.
Did you get any error prompt? I need to know more specific about your issue, such as your Excel version. The more detailed you describe the error, the faster we can understand and solve it.
This comment was minimized by the moderator on the site
Hello,

the code worked initially, but after I duplicated the worksheet, it stayed for after 24 hours then all the code disappeared. And now I can’t access the worksheet.

it keeps telling me incorrect password. And the code have disappeared. .
This comment was minimized by the moderator on the site
Hello, I used the above code and got the following error message:
"Code execution has been interrupted". When I click on Debug, Line 20 "Selection.ClearContents" is highlighted.

When I initially entered the code, it worked correctly.

I changed "Table" to the name of the table and change the column to the name of the column I am using. I also changed the "Selection.Offset (x,-x).Select" to match my needs.


Any suggestions as to why this is occurring?
This comment was minimized by the moderator on the site
Try this Vba code for add new line in you table

Sub Tab_Line_Add()
Dim pswStr As String
pswStr = "123"
On Error Resume Next
Application.ScreenUpdating = False
ActiveSheet.Unprotect Password:=pswStr
ActiveSheet.Range("D8").Select
'D8 is tabel header
Range("Table1[[#Headers],[Total]]").Select
Selection.End(xlDown).Select
Selection.ListObject.ListRows.Add AlwaysInsert:=False
ActiveSheet.Protect Password:=pswStr

End Sub
.
This comment was minimized by the moderator on the site
using the suggested (Selection.ListObject.ListRows.Add AlwaysInsert:=False) fixed a similar problem for me with the original code, where a new full row (extending down cell contained formulas) would not be added to the table on a much wider table 51 columns. So thanks for sharing and fixing Mac.
This comment was minimized by the moderator on the site
Hi Mac,
Thanks for sharing.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations