IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Macros et VBA Excel Discussion :

Impossible de saisir un mot de passe pour déprotéger le projet vba via sendkey


Sujet :

Macros et VBA Excel

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Doubs (Franche Comté)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Service public

    Informations forums :
    Inscription : Décembre 2014
    Messages : 16
    Points : 8
    Points
    8
    Par défaut Impossible de saisir un mot de passe pour déprotéger le projet vba via sendkey
    Bonjour à tous, la discussion n'est pas récente, mais je souhaite utiliser cette macro pour un projet de mise a jour, le fait est que je ne peux pas manuellement aller vers les 35 postes qui utilisent mon classeur pour le déprotéger, je diffuse un fichier.xls qui modifie celui déja présent sur chaque machine et le met à jour, seulement lorsque la macro se lance, je reste bloqué sur la fenetre ou l'on est censé rentrer le mot de passe pour déprotéger le projet avant d'appliquer la modification sur les modules.. malgrès les différents essais ( sendkeys avant ou après , utilisation de la fonction wait de sendkey, je ne parviens pas a faire entrer les caractères de mon mot de passe dans la fenêtre de selection... par contre manuellement cela fonctionne ?!?

    Auriez vous une solution pour m'aider à y arriver :-)

    Merci d'avance à ceux qui m'aideront dans ma programation. ( je précise que j'utilise excel 2002 SP3 avec Xp 2002 SP3 et que je n'ai pas accès au compte administrateur)

    Je précise que la variable "motdepasse" prends correctement les caractères, mais la procédure sendkey ne semble pas envoyer les caractères dans la fenetre de selaction de mot de passe

    Voici mon bout de code et merci à MichD qui l'as partagé


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
     
    Sub OterProtectionPRojetVBA()
    On Error GoTo 1
    Dim Wk As Workbook, motdepasse As String
    Dim NomDuModule As String, FichierÀOuvrir As String
    Dim LeCodeAInsérer As String
    'Créateur MichD
    '**********Variables à définir*************
    'Supposons nom du module source et de
    'destination est le même: MichD
    'Le module "MichD" existe déjà dans le fichier de destination.
    NomDuModule = "Module2" '------------------------------------------- nom module source
    motdepasse = "test" '---------------------------------------- mot de passe fichiers
    FichierÀOuvrir = Application.GetOpenFilename()
    '*******************************************
    Application.ScreenUpdating = False
    'Définir la variable LeCodeAInsérer avec le contenu du
    'module MichD existant dans le module "MichD" de ce fichier
    With ThisWorkbook.VBProject.VBComponents("module2").CodeModule '----- module cible
        If .CountOfLines > 0 Then
            LeCodeAInsérer = .Lines(1, .CountOfLines)
        End If
    End With
    'Ouvrir le classeur contenant le module à modifier
     
    Application.EnableEvents = False
    'ton code d'ouverture du fichier A
    Set Wk = Workbooks.Open(FichierÀOuvrir)
     
    'Wk.Visible = False
     
    'Déprotéger le projetVBA du fichier qu'on vient d'ouvrir
     Application.EnableEvents = True
     
     
    UnprotectVBProject Wk, motdepasse
     
     
    'Supprimer le code du module "MichD" qu'on vient d'ouvrir
    Call Supprime__Code_Module(Wk, NomDuModule)
    'Ajouter le code du module "MichD" de ce fichier au
    'Module "MichD" du fichier qu'on vient d'ouvrir
    Call Insérer_Nouveau_Code(Wk, NomDuModule, LeCodeAInsérer)
    'Fermeture du classeur modifié
    Wk.Close True
     
    'Ouvrir le classeur - Vérifier si le job est bien fait!
    ThisWorkbook.Application.Visible = True
    GoTo 2
    1:
    msgbox "une erreur est survenue, veuillez quitter le programme et recommencer ou prendre contact avec xxxxxxx"
    'Application.Quit
     
    2:
    CreateObject("Wscript.shell").Popup "La mise à jour s'est effectuée avec succès, le programme va sauvegarder les changements veuillez patienter...", 5, "Effectué", vbExclamation
    ThisWorkbook.Application.Visible = False
    patience1.Show
    CreateObject("Wscript.shell").Popup "La sauvegarde est effectuée, vous pouvez continuer a travailler sur le programme.", 5, "Terminé", vbExclamation
     
    'Application.Quit
    End Sub
     
    '-----------------------------------------
    Sub UnprotectVBProject(WB As Workbook, ByVal motdepasse As String)
      Dim vbProj As Object
      Set vbProj = WB.VBProject
      'Ne peut procéder si le projet est non-protégé.
      If vbProj.Protection <> 1 Then Exit Sub
      Set Application.VBE.ActiveVBProject = vbProj
      'Utilisation de "SendKeys" Pour envoyer le mot de passe.
      msgbox motdepasse
    Application.wait (Now() + TimeValue("00:00:01"))
     
    Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
    Application.wait (Now() + TimeValue("00:00:01"))
     SendKeys motdepasse, True
      SendKeys "{ENTER}", True
     
    msgbox "apres execute"
      Application.wait (Now + TimeValue("00:00:01"))
     
    End Sub
    '-----------------------------------------
    Sub Supprime__Code_Module(Wk As Workbook, NomModule As String)
    With Wk.VBProject.VBComponents(NomModule).CodeModule
        .DeleteLines 1, .CountOfLines
    End With
    End Sub
    '-----------------------------------------
    Sub Insérer_Nouveau_Code(Wk As Workbook, NomDuModule As String, Code As String)
    With Wk.VBProject.VBComponents(NomDuModule).CodeModule
        .AddFromString Code
    End With
    End Sub

  2. #2
    Rédacteur/Modérateur

    Avatar de Jean-Philippe André
    Homme Profil pro
    Développeur VBA/C#/VB.Net/Power Platform
    Inscrit en
    Juillet 2007
    Messages
    14 594
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Canada

    Informations professionnelles :
    Activité : Développeur VBA/C#/VB.Net/Power Platform
    Secteur : Finance

    Informations forums :
    Inscription : Juillet 2007
    Messages : 14 594
    Points : 34 266
    Points
    34 266
    Par défaut
    Salut,

    il semblerait qu'on puisse arriver à faire ce que tu veux en "catchant" la bonne fenêtre.

    Une solution trouvée sur un blog anglophone :
    http://www.siddharthrout.com/2013/04...that-you-know/
    Unprotecting
    VBA
    Project
    Password
    (Using
    a
    password
    that
    you
    know)
    21

    Posted on: 04-24-2013 by: Siddharth Rout

    First things first. This is NOT about hacking the VBA Project Password. If you have landed on this page to expect to see how it is hacked then I would recommend you to search somewhere else. This article is about unlocking the VBA Project password if you KNOW the password.

    Recently while answering a question, I came across this interesting question. I know many people in the past have been using Sendkeys to achieve this. I have been thinking about a different approach but could never find a time for this. Finally, yesterday, I took the plunge!

    Below are VBA/VB.Net examples on how to unlock the VBA Password. VB6 example is same as VBA example. Before we get into the actual code, let’s understand the logic of the code.

    Let’s say we have a workbook whose VBA project looks like this currently.

    LOGIC:

    Find the Handle of the VBAProject Password window using FindWindow
    Once that is found, find the handle of the Edit Box in that window using FindWindowEx
    Once the handle of the Edit Box is found, simply use SendMessage to write to it.
    Find the handle of the Buttons in that window using FindWindowEx
    Once the handle of the OK button is found, simply use SendMessage to click it.

    RECOMMENDATION:

    1. For API’s THIS is the best link I can recommend.

    2. If you wish to become good at API’s like FindWindow, FindWindowEx and SendMessage then get a tool that gives you a graphical view of the system’s processes, threads, windows, and window messages. For Ex: uuSpy or Spy++.

    Here is what Spy++ will show you for VBAProject Password window

    VBA

    Open a new Excel instance and paste the below code in a module. I have commented the code so you shouldn’t have any problem understanding it.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
     
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
     
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
    (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
    ByVal lpsz2 As String) As Long
     
    Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
    (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
     
    Private Declare Function GetWindowTextLength Lib "user32" Alias _
    "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
     
    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
     
    Dim Ret As Long, ChildRet As Long, OpenRet As Long
    Dim strBuff As String, ButCap As String
    Dim MyPassword As String
     
    Const WM_SETTEXT = &HC
    Const BM_CLICK = &HF5
     
    Sub UnlockVBA()
        Dim xlAp As Object, oWb As Object
     
        Set xlAp = CreateObject("Excel.Application")
     
        xlAp.Visible = True
     
        '~~> Open the workbook in a separate instance
        Set oWb = xlAp.Workbooks.Open("C:\Sample.xlsm")
     
        '~~> Launch the VBA Project Password window
        '~~> I am assuming that it is protected. If not then
        '~~> put a check here.
        xlAp.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
     
        '~~> Your passwword to open then VBA Project
        MyPassword = "Blah Blah"
     
        '~~> Get the handle of the "VBAProject Password" Window
        Ret = FindWindow(vbNullString, "VBAProject Password")
     
        If Ret <> 0 Then
            'MsgBox "VBAProject Password Window Found"
     
            '~~> Get the handle of the TextBox Window where we need to type the password
            ChildRet = FindWindowEx(Ret, ByVal 0&, "Edit", vbNullString)
     
            If ChildRet <> 0 Then
                'MsgBox "TextBox's Window Found"
                '~~> This is where we send the password to the Text Window
                SendMess MyPassword, ChildRet
     
                DoEvents
     
                '~~> Get the handle of the Button's "Window"
                ChildRet = FindWindowEx(Ret, ByVal 0&, "Button", vbNullString)
     
                '~~> Check if we found it or not
                If ChildRet <> 0 Then
                    'MsgBox "Button's Window Found"
     
                    '~~> Get the caption of the child window
                    strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr$(0))
                    GetWindowText ChildRet, strBuff, Len(strBuff)
                    ButCap = strBuff
     
                    '~~> Loop through all child windows
                    Do While ChildRet <> 0
                        '~~> Check if the caption has the word "OK"
                        If InStr(1, ButCap, "OK") Then
                            '~~> If this is the button we are looking for then exit
                            OpenRet = ChildRet
                            Exit Do
                        End If
     
                        '~~> Get the handle of the next child window
                        ChildRet = FindWindowEx(Ret, ChildRet, "Button", vbNullString)
                        '~~> Get the caption of the child window
                        strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr$(0))
                        GetWindowText ChildRet, strBuff, Len(strBuff)
                        ButCap = strBuff
                    Loop
     
                    '~~> Check if we found it or not
                    If OpenRet <> 0 Then
                        '~~> Click the OK Button
                        SendMessage ChildRet, BM_CLICK, 0, vbNullString
                    Else
                        MsgBox "The Handle of OK Button was not found"
                    End If
                Else
                     MsgBox "Button's Window Not Found"
                End If
            Else
                MsgBox "The Edit Box was not found"
            End If
        Else
            MsgBox "VBAProject Password Window was not Found"
        End If
    End Sub
     
    Sub SendMess(Message As String, hwnd As Long)
        Call SendMessage(hwnd, WM_SETTEXT, False, ByVal Message)
    End Sub
    Cycle de vie d'un bon programme :
    1/ ça fonctionne 2/ ça s'optimise 3/ ça se refactorise

    Pas de question technique par MP, je ne réponds pas

    Mes ouvrages :
    Apprendre à programmer avec Access 2016, Access 2019 et 2021

    Apprendre à programmer avec VBA Excel
    Prise en main de Dynamics 365 Business Central

    Pensez à consulter la FAQ Excel et la FAQ Access

    Derniers tutos
    Excel et les paramètres régionaux
    Les fichiers Excel binaires : xlsb,

    Autres tutos

  3. #3
    Expert éminent sénior
    Homme Profil pro
    aucune
    Inscrit en
    Septembre 2011
    Messages
    8 203
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Septembre 2011
    Messages : 8 203
    Points : 14 354
    Points
    14 354
    Par défaut
    Bonjour,

    J'ai trouvé ce code (non testé). Il faut ouvrir une nouvelle instance d'Excel. Tu ouvres ensuite un nouveau classeur et, dans un module, tu colles :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
     
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
    (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
    ByVal lpsz2 As String) As Long
     
    Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
    (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
     
    Private Declare Function GetWindowTextLength Lib "user32" Alias _
    "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
     
    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
     
    Dim Ret As Long, ChildRet As Long, OpenRet As Long
    Dim strBuff As String, ButCap As String
    Dim MyPassword As String
     
    Const WM_SETTEXT = &HC
    Const BM_CLICK = &HF5
     
    Sub UnlockVBA()
        Dim xlAp As Object, oWb As Object
     
        Set xlAp = CreateObject("Excel.Application")
     
        xlAp.Visible = True
     
        '~~> Open the workbook in a separate instance
        Set oWb = xlAp.Workbooks.Open("C:\Sample.xlsm")
     
        '~~> Launch the VBA Project Password window
        '~~> I am assuming that it is protected. If not then
        '~~> put a check here.
        xlAp.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
     
        '~~> Your passwword to open then VBA Project
        MyPassword = "Blah Blah"
     
        '~~> Get the handle of the "VBAProject Password" Window
        Ret = FindWindow(vbNullString, "VBAProject Password")
     
        If Ret <> 0 Then
            'MsgBox "VBAProject Password Window Found"
     
            '~~> Get the handle of the TextBox Window where we need to type the password
            ChildRet = FindWindowEx(Ret, ByVal 0&, "Edit", vbNullString)
     
            If ChildRet <> 0 Then
                'MsgBox "TextBox's Window Found"
                '~~> This is where we send the password to the Text Window
                SendMess MyPassword, ChildRet
     
                DoEvents
     
                '~~> Get the handle of the Button's "Window"
                ChildRet = FindWindowEx(Ret, ByVal 0&, "Button", vbNullString)
     
                '~~> Check if we found it or not
                If ChildRet <> 0 Then
                    'MsgBox "Button's Window Found"
     
                    '~~> Get the caption of the child window
                    strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr$(0))
                    GetWindowText ChildRet, strBuff, Len(strBuff)
                    ButCap = strBuff
     
                    '~~> Loop through all child windows
                    Do While ChildRet <> 0
                        '~~> Check if the caption has the word "OK"
                        If InStr(1, ButCap, "OK") Then
                            '~~> If this is the button we are looking for then exit
                            OpenRet = ChildRet
                            Exit Do
                        End If
     
                        '~~> Get the handle of the next child window
                        ChildRet = FindWindowEx(Ret, ChildRet, "Button", vbNullString)
                        '~~> Get the caption of the child window
                        strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr$(0))
                        GetWindowText ChildRet, strBuff, Len(strBuff)
                        ButCap = strBuff
                    Loop
     
                    '~~> Check if we found it or not
                    If OpenRet <> 0 Then
                        '~~> Click the OK Button
                        SendMessage ChildRet, BM_CLICK, 0, vbNullString
                    Else
                        MsgBox "The Handle of OK Button was not found"
                    End If
                Else
                     MsgBox "Button's Window Not Found"
                End If
            Else
                MsgBox "The Edit Box was not found"
            End If
        Else
            MsgBox "VBAProject Password Window was not Found"
        End If
    End Sub
     
    Sub SendMess(Message As String, hwnd As Long)
        Call SendMessage(hwnd, WM_SETTEXT, False, ByVal Message)
    End Sub
    J'ai la flemme de traduire les commentaires. Tu dois exécuter :
    après avoir mis ton mot de passe ici :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    MyPassword = "Blah Blah"
    Pour ouvrir une nouvelle instance d'Excel, télécharge le fichier joint en modifiant avec le bloc notes le chemin du fichier "EXCEL.EXE" :
    Excel.zip
    Cordialement.

    Daniel

    La plus perdue de toutes les journées est celle où l'on n'a pas ri. Chamfort

  4. #4
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Doubs (Franche Comté)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Service public

    Informations forums :
    Inscription : Décembre 2014
    Messages : 16
    Points : 8
    Points
    8
    Par défaut
    Oh ! Merci pour la réponse super rapide...
    je vais tester ça cet après midi et je te rends réponse

    Merci d'avance

  5. #5
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Doubs (Franche Comté)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Service public

    Informations forums :
    Inscription : Décembre 2014
    Messages : 16
    Points : 8
    Points
    8
    Par défaut
    Me revoilà,

    Alors il y a deux points négatifs dans cette procédure:

    1) Je dois, si j'ai bien compris, chaque fois transmettre le classeur de mise à jour, le classeur de procédure de déblocage et le fichier .bat, ce qui m'ennuie vraiment.

    2)Les personnes à qui j'envoie cette mise à jour sont des novices qui ne connaissent pas grand chose aux ordinateurs en général, je cherchait une manière la plus simple possible pour mettre à jour leurs classeurs respectifs sans les bombarder de fichiers ou de procédures...

    Est ce que j'aurais pas meilleur temps de passer sous access pour faciliter la mise à jour ?
    Ou carément désécuriser définitivement mon classeur pour faciliter la mise à jour et prendre le risque que certains mâlins aillent bidouiller mes modules ?

    L'ennui c'est que mes connaissances en programation vba sont assez limitées et que je n'ai encore jamais touché access mais que j'ai souvent entendu parler de ses mérites...

    J'attends vos conseils.

  6. #6
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 274
    Points
    11 274
    Par défaut
    Salut, il faudrait faire une recherche externe à ce forum sur : Laurent Longre, il avait publié,il me semble, qqch sur ce sujet.

  7. #7
    Expert éminent sénior


    Profil pro
    Inscrit en
    Juin 2003
    Messages
    14 008
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 14 008
    Points : 20 038
    Points
    20 038
    Par défaut
    Bonjour,

    Citation Envoyé par hartarus Voir le message
    ...
    2)Les personnes à qui j'envoie cette mise à jour sont des novices qui ne connaissent pas grand chose aux ordinateurs en général, je cherchait une manière la plus simple possible pour mettre à jour leurs classeurs respectifs sans les bombarder de fichiers ou de procédures...
    ....
    et tu veux modifier tes macros par le code ? c'est pas la bonne solution c'est déjà une opération hasardeuse , tu vas au devant de problèmes de paramétrage des sécurités sur tes postes....

    essai de faire cela plus "proppemment" en séparant tes classeur excel en deux , un classeur pour les données un autre ( add-on ..) pour le code, ainsi pour tes futures mise à jour de macros tu n'as qu'as remplacer ton classeur macros..

  8. #8
    Expert éminent sénior
    Homme Profil pro
    aucune
    Inscrit en
    Septembre 2011
    Messages
    8 203
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Septembre 2011
    Messages : 8 203
    Points : 14 354
    Points
    14 354
    Par défaut
    Ou alors rapatrie les classeurs par courrier, si possible, fais les modifs et retourne-les.
    Cordialement.

    Daniel

    La plus perdue de toutes les journées est celle où l'on n'a pas ri. Chamfort

  9. #9
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 274
    Points
    11 274
    Par défaut
    Salut, j'ai trouvé ceci : code de Laurent Longre, à adapter à ton projet

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    Option Explicit
     
    Private Declare Function FindWindowA Lib "User32" _
                                         (ByVal lpClassName As String, _
                                          ByVal lpWindowName As String) As Long
     
    Private Declare Function GetForegroundWindow Lib "User32" () As Long
     
    Private Declare Function SetForegroundWindow Lib "User32" _
                                                 (ByVal hWnd As Long) As Long
     
    Function Déprotège(Classeur As String, MdP As String) As Boolean
    Dim XLhWnd As Long, VBEhWnd As Long, CurhWnd As Long
    Dim Wbk As Workbook
     
        On Error Resume Next
        Set Wbk = Workbooks(Dir$(Classeur))
        On Error GoTo Fin
        If Not Wbk Is Nothing Then
            If Wbk.FullName <> Classeur Then Exit Function
            If Not Wbk.Saved Then Wbk.Save
        Else: Application.ScreenUpdating = False
        End If
     
        CurhWnd = GetForegroundWindow
        XLhWnd = FindWindowA(vbNullString, Application.Caption)
     
        With Application.VBE
            VBEhWnd = FindWindowA(vbNullString, .MainWindow.Caption)
            If CurhWnd = XLhWnd Then SetForegroundWindow VBEhWnd
            .CommandBars.FindControl(ID:=2557).Execute
            ' NE PAS EFFACER, même si le classeur est déjà ouvert !!!!!!
            Workbooks.Open Classeur
            If ActiveWorkbook.VBProject.Protection = vbext_pp_locked Then
                SendKeys "~" & MdP & "~", True
                .ActiveCodePane.Window.Close
            End If
        End With
     
        SetForegroundWindow CurhWnd
        Déprotège = True
        Exit Function
    Fin:
    End Function
     
    Sub TestDeProt()
    Dim Classeur As String
     
        Classeur = ThisWorkbook.Path & "\" & "Test.xls"
     
        If Not Déprotège(Classeur, "MotDePasse") Then
            MsgBox "Erreur"
        Else
            MsgBox "Projet VBA déprotégé."
        End If
    End Sub

  10. #10
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2014
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Doubs (Franche Comté)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Service public

    Informations forums :
    Inscription : Décembre 2014
    Messages : 16
    Points : 8
    Points
    8
    Par défaut
    Bonjour à vous et merci de vous pencher sur mon problème et de me proposer vos idées !

    Citation Envoyé par bbil Voir le message
    Bonjour,


    et tu veux modifier tes macros par le code ? c'est pas la bonne solution c'est déjà une opération hasardeuse , tu vas au devant de problèmes de paramétrage des sécurités sur tes postes....

    essai de faire cela plus "proppemment" en séparant tes classeur excel en deux , un classeur pour les données un autre ( add-on ..) pour le code, ainsi pour tes futures mise à jour de macros tu n'as qu'as remplacer ton classeur macros..
    Oui je modifie par code, c'est plus simple pour moi d'envoyer un fichier de mise à jour, que de chaque fois renvoyer un classeur excel de 5 mo
    Pour l'idée de séparer en deux classeurs, connaissant les utilisateurs de ce classeurl, il vaut mieux pas... ils seraient capable de soit : supprimer un des deux classeurs soir lancer le mauvais, mais l'idées serait adaptée pour un public qui connais un peu mieux...

    Citation Envoyé par Daniel.C Voir le message
    Ou alors rapatrie les classeurs par courrier, si possible, fais les modifs et retourne-les.
    Bonne idée mais bien plus compliquée pour moi pour m'assurer de récup tous les classeurs et de les modifier un par un, je fait environ deux à 3 modif par mois, sur 35 classeur va va me faire un sacré boulot.

    Citation Envoyé par kiki29 Voir le message
    Salut, j'ai trouvé ceci : code de Laurent Longre, à adapter à ton projet

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    Option Explicit
     
    Private Declare Function FindWindowA Lib "User32" _
                                         (ByVal lpClassName As String, _
                                          ByVal lpWindowName As String) As Long
     
    Private Declare Function GetForegroundWindow Lib "User32" () As Long
     
    Private Declare Function SetForegroundWindow Lib "User32" _
                                                 (ByVal hWnd As Long) As Long
     
    Function Déprotège(Classeur As String, MdP As String) As Boolean
    Dim XLhWnd As Long, VBEhWnd As Long, CurhWnd As Long
    Dim Wbk As Workbook
     
        On Error Resume Next
        Set Wbk = Workbooks(Dir$(Classeur))
        On Error GoTo Fin
        If Not Wbk Is Nothing Then
            If Wbk.FullName <> Classeur Then Exit Function
            If Not Wbk.Saved Then Wbk.Save
        Else: Application.ScreenUpdating = False
        End If
     
        CurhWnd = GetForegroundWindow
        XLhWnd = FindWindowA(vbNullString, Application.Caption)
     
        With Application.VBE
            VBEhWnd = FindWindowA(vbNullString, .MainWindow.Caption)
            If CurhWnd = XLhWnd Then SetForegroundWindow VBEhWnd
            .CommandBars.FindControl(ID:=2557).Execute
            ' NE PAS EFFACER, même si le classeur est déjà ouvert !!!!!!
            Workbooks.Open Classeur
            If ActiveWorkbook.VBProject.Protection = vbext_pp_locked Then
                SendKeys "~" & MdP & "~", True
                .ActiveCodePane.Window.Close
            End If
        End With
     
        SetForegroundWindow CurhWnd
        Déprotège = True
        Exit Function
    Fin:
    End Function
     
    Sub TestDeProt()
    Dim Classeur As String
     
        Classeur = ThisWorkbook.Path & "\" & "Test.xls"
     
        If Not Déprotège(Classeur, "MotDePasse") Then
            MsgBox "Erreur"
        Else
            MsgBox "Projet VBA déprotégé."
        End If
    End Sub
    Cette fonction doit sûrement fonctionner, seulement mes connaissances s'arrêtent là, je n'ai jamais intégré de fonction dans mes macros, serait tu assez gentil, soit pour m'aider à intégrer cette fonction dans mon code, soit en me disant comment faire ?

    Désolé mais je n'ai jamais eu à utiliser de fonction dans mes macros, je ne sait donc pas comment m'y prendre :-) je suis un débutant

  11. #11
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 274
    Points
    11 274
    Par défaut
    Cette fonction doit sûrement fonctionner
    Il serait préférable, avant de poursuivre, de savoir si elle remplit sa fonction de déverrouillage pour ton fichier, et cela seul toi peut nous le dire.

    La proposition pertinente de bbil serait également à appliquer :
    Essaie de faire cela plus proprement en séparant tes classeurs excel en deux , un classeur pour les données un autre ( add-on ..) pour le code, ainsi pour tes futures mises à jour de macros tu n'auras qu'à remplacer ton classeur macros ..

  12. #12
    Expert éminent sénior

    Profil pro
    Conseil, Formation, Développement - Indépendant
    Inscrit en
    Février 2010
    Messages
    8 417
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Conseil, Formation, Développement - Indépendant

    Informations forums :
    Inscription : Février 2010
    Messages : 8 417
    Points : 16 260
    Points
    16 260
    Par défaut
    Bonjour

    Tu sembles vouloir créer une usine à gaz. Tu te dis débutant : c'est un gros risque que l'usine à gaz explose...

    1ère remarque : si l'analyse préalable est correctement faite, il n'y a pas de raison de mettre à jour le code VBA de façon régulière : 2 à 3 fois par mois ce n'est pas normal.
    Il serait bien de savoir ce qui motive tes modifications. Peut-être une optimisation du code initial est-elle à faire une fois pour toutes.
    Si tu ne connais pas les fonctions, il est probable que tu maîtrise mal le VBA et que tes choix techniques soient à améliorer.

    Si le code évolue, comme suggéré il est préférable de séparer données et code : dans ce cas le code est à placer dans un module complémentaire xla. Il est installé sur Excel et ne peut être confondu avec un classeur standard.
    Chris
    PowerQuery existe depuis plus de 13 ans, est totalement intégré à Excel 2016 &+. Utilisez-le !

    Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson.
    Confucius

    ----------------------------------------------------------------------------------------------
    En cas de résolution, n'hésitez pas cliquer sur c'est toujours apprécié...

  13. #13
    Expert éminent sénior
    Avatar de kiki29
    Homme Profil pro
    ex Observeur CGG / Analyste prog.
    Inscrit en
    Juin 2006
    Messages
    6 132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Finistère (Bretagne)

    Informations professionnelles :
    Activité : ex Observeur CGG / Analyste prog.

    Informations forums :
    Inscription : Juin 2006
    Messages : 6 132
    Points : 11 274
    Points
    11 274
    Par défaut
    A voir également, dans le prolongement du post#11 : AutoUpdate d'une macro-complémentaire Add-In

Discussions similaires

  1. Réponses: 3
    Dernier message: 18/12/2007, 17h21
  2. Impossible de saisir le mot de passe de session
    Par GD91 dans le forum Windows XP
    Réponses: 4
    Dernier message: 20/10/2006, 19h22
  3. Supprimer le mot de passe pour sa
    Par tripper.dim dans le forum MS SQL Server
    Réponses: 9
    Dernier message: 13/01/2005, 12h13
  4. Réponses: 4
    Dernier message: 29/11/2004, 22h53

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo