Search code examples
vbacsvvariablesms-worduserform

Look up UserForm Caption Variable in CSV to get other values


I want a Word Macro that will insert dynamic signatures (up to three) and have never done any VBA before (more of a Powershell guy...).

To do that, I've created a UserForm in the "developer" interface with 3 frames and plenty of radio buttons containing as caption the names of the people that will be able to sign.

As there are 60 peoples (or more) that will be able to sign, I have thought about having a CSV file with them containing their "Name, Department, Function).

My issue is I have no clue on how to read a CSV, compare it with my caption (let's say Caption = "Jon Swiss") and initialize the variable for three other values.

I have tagged my document with some bookmarks (that works with the caption only).

I don't know if you need the script I have done (nothing about the CSV - sorry...)

Private Sub RHBtn_Accepter_Click_Click()
'Initialisation
Dim i As Integer
'***
'       Signature 1
'*** 
'Pour chaque valeur possible
  For i = 1 To Me.Controls.Count
    'Si i plus petit que le nombre de valeur définie
    If i < Me.Controls.Count Then
      Set MyControl = Me.Controls.Item(i)
      'Si control dispose du tag RHSign1
      If MyControl.Tag = "RHSign1" Then
         'Si une valeur est activée
         If MyControl.Value = True Then
            'Mise en variable du nom en Sign1
            RHSignature1 = MyControl.Caption
            Exit For
         End If
      End If
    End If
  Next i

'***
'       Gettings CSV Value
'***

'***
'       Tagging the bookmarks
'***
           If ActiveDocument.Bookmarks.Exists("RhSignet1") = True Then
              Selection.GoTo What:=wdGoToBookmark, Name:="RhSignet1"
              Selection.TypeText Text:=RHSignature1
           End If
End Sub

Solution

  • Thank you for your help.

    I found a way with CSV.

      'Répertoire
    directory = "H:\@SCRIPTS\VBA_MacroWord_DigitRH\"
    FileName = "BaseSignatureTest.csv"
    'Ouverture de la connexion CSV
    Set rs = CreateObject("ADODB.Recordset")
    strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
    & "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
    strSQL = "SELECT * FROM " & FileName
    rs.Open strSQL, strcon, 3, 3
    rs.MoveFirst
    
    Do
       col1 = rs("Nom")
       col2 = rs("Fonction")
       col3 = rs("DPT")
       col4 = rs("Signature")
       rs.MoveNext
    
       'Si une valeur a été trouvée et qu'elle corresponds, définition des valeurs
       If col1 = RHSignature2 Then
       MsgBox "Signature2"
       MsgBox col1
       MsgBox col2
       MsgBox col3
       MsgBox col4
    

    Seems to be working. Maybe there is a better way. But thanks to everyone that took some time that took the time to read me. Have a nice week, Jon