Consejo: Otros idiomas son traducidos por Google. Puedes visitar el English versión de este enlace.
Iniciar sesión
x
or
x
x
Suscríbete
x

or

¿Cómo crear listas desplegables dependientes en un documento de Word?


Como se muestra en la imagen de la izquierda, debe limitar las opciones en la segunda lista desplegable en función de la opción en la primera lista desplegable, ¿cómo puede hacerlo? Este artículo le mostrará el método para crear listas desplegables dependientes en un documento de Word.

Crea listas desplegables dependientes en Word con código VBA


Crea listas desplegables dependientes en Word con código VBA

El siguiente código de VBA puede ayudarlo a crear listas desplegables dependientes en un documento de Word. Por favor siga las instrucciones paso a paso.

1. En primer lugar, debe insertar dos listas desplegables en su documento de Word. Hacer clic Desarrollador > Formas heredadas > Campo de formulario desplegable. Ver captura de pantalla:

2. Haga clic derecho en la primera lista desplegable (esta lista desplegable debe ser la principal) y haga clic en Propiedades. Ver captura de pantalla:

3. En la apertura Opciones de campo de formulario desplegable cuadro de diálogo, necesita:

3.1 Introduzca la categoría en el Elemento desplegable cuadro y luego haga clic en el Añadir botón, repita la operación hasta que todas las categorías se agreguen al cuadro de lista desplegable Artículos en.

3.2 Enter ddfood en el Guardar encajonar.

3.3 Haga clic en OK botón. Ver captura de pantalla:

4. Haga clic derecho en la segunda lista desplegable, haga clic en Propiedades para abrir su Opciones de campo de formulario desplegable cuadro de diálogo, y en el cuadro de diálogo, escriba ddcategoria en el Guardar cuadro y haga clic en el OK botón. Ver captura de pantalla:

5. presione el otro + F11 teclas para abrir el Microsoft Visual Basic para aplicaciones ventana.

6. En el Microsoft Visual Basic para aplicaciones ventana, haga clic recuadro > Módulo, luego copia debajo del código VBA en la ventana del Módulo.

Código VBA: crea una lista desplegable dependiente en Word

Sub Populateddfood()
'Update by Extendoffice 2018/10/25
    Dim xDirection As FormField
    Dim xState As FormField
    On Error Resume Next
    Set xDirection = ActiveDocument.FormFields("ddfood")
    Set xState = ActiveDocument.FormFields("ddCategory")
    If ((xDirection Is Nothing) Or (xState Is Nothing)) Then Exit Sub
    With xState.DropDown.ListEntries
        .Clear
        Select Case xDirection.Result
            Case "Fruit"
                .Add "Apple"
                .Add "Banana"
                .Add "Peach"
                .Add "Lychee"
                .Add "Watermelon"
            Case "Vegetable"
                .Add "Cabbage"
                .Add "Onion"
            Case "Meat"
                .Add "Pork"
                .Add "Beef"
                .Add "Mutton"
        End Select
    End With
End Sub

Notas:

1. En el código, cambie los elementos en cada caso según lo necesite.

2. ddfood y ddcategoria debe coincidir con las opciones de Marcador que ingresó en los dos anteriores Opciones de campo de formulario desplegable Cuadros de diálogo.

7. Guarde el código y vuelva al documento.

8. Haga clic derecho en la primera lista desplegable y haga clic en Propiedades para abrir el Opciones de campo de formulario desplegable caja de diálogo. En el cuadro de diálogo, seleccione el nombre de la Macro anterior (aquí está Popolateddfood) de la Salida lista desplegable, y luego haga clic en OK botón.

9. Ahora haga clic Desarrollador > Restringir la edición como se muestra a continuación.

10. En el Restringir la edición panel, necesitas:

10.1), compruebe el Permitir sólo este tipo de edición. en el documento caja;

10.2) Seleccionar Rellenar formularios opción de la lista desplegable;

10.3) Haga clic en Sí, Comience a hacer cumplir la protección botón;

10.4) en el Empezar a aplicar la protección diálogo, ingrese la contraseña y haga clic en el OK botón. Ver captura de pantalla:

Ahora se crean las listas desplegables dependientes. Al seleccionar Fruta de la primera lista desplegable, solo las categorías de fruta se pueden seleccionar en la segunda.



Herramientas recomendadas de productividad de palabras

Kutools para Word: más que las funciones avanzadas de 100 para Microsoft Word, ahorre su tiempo de 50

  • Las operaciones complicadas y repetidas se pueden realizar una sola vez en segundos.
  • Inserte varias imágenes a través de carpetas en el documento de Word a la vez.
  • Combine y combine varios archivos de Word en carpetas en uno con su orden deseado.
  • Divida el documento actual en documentos separados según el encabezado 1, el salto de sección u otros criterios.
  • Convierta archivos entre Doc y Docx, Docx y PDF, colección de herramientas para conversiones y selección comunes, y así...
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Amy · 15 days ago
    Thank you for this very useful resource.

    Is it possible to repeat the same dependent drop down multiple times within a form?

    I need the form filler to assign a category to each new row (but with the same options each time).I have successfully created the drop downs but when I restrict editing to test they seem to reset themselves as I work down the rows.

    Thanks
    Amy
  • To post as a guest, your comment is unpublished.
    Eduardo Gallardo · 24 days ago
    Hello, How can i duplicate the categories box? I have used the code above and works well, but only for one box. What do I do in the code if for example if I need to select up to 3 fruits once I have selected the Fruit group? I am duplicating the field I created but only one works.
    ---------------------
    Select
    FRUIT: banana
    apple
    "select item"


    ----------------------------------
    Select
    Vegetable: Cabbage
    onion
    "select item"
  • To post as a guest, your comment is unpublished.
    Ed · 24 days ago
    Is there a way to add multiple category fields based on the one selection? for example I need say Select "Wine" but i need to be able to select 5 options (fruity, red, strong, etc...) from the 10 possible options in the second drop-down field list. I followed instructions above and works well on one field with one other dependent field only. But I need 5 dependent fields, all the same triggered by the one field in this case "wine". I duplicate the drop-down field it doesn't work, I am trying to add a second field to the code, but not sure how: ActiveDocument.FormFields("ddCategory") and ("ddCategory2")
  • To post as a guest, your comment is unpublished.
    SRMoritz · 2 months ago
    HI I got the drop downs to work. I have a question
    When I make the selection for the first drop down, Is there any way to automate the coordinating and related selections for the following drop downs? For example. I have a parent drop down Attorney, the two child drop downs are Title and Phone number respectively. When I select the attorney name, I would like the related child drop downs to auto populate the title and phone number. How would I be able to do that?

    Thanks in advance.

    Sylvia
    • To post as a guest, your comment is unpublished.
      crystal · 1 months ago
      Good day,
      Sorry can't help you with that yet. Thanks for your comment.
  • To post as a guest, your comment is unpublished.
    Paul · 2 months ago
    Hi,

    How do we text wrap? I followed the step and it works fine except that when the second list is too long, it goes beyond the page. Is there a way to have it automatically wrap?
    • To post as a guest, your comment is unpublished.
      crystal · 1 months ago
      Hi Paul,
      Sorry can't help you with that yet. Thanks for your comment.
  • To post as a guest, your comment is unpublished.
    Marc · 3 months ago
    Hi There,
    are there restrictions with the name in the field (e.g. 2 words, or use of special caracters)?
    Like Field A (Company Name) Field B (Director Name, like Jack Black).
    Thanks!
    • To post as a guest, your comment is unpublished.
      crystal · 1 months ago
      Hi Marc,
      Yes, there are restrictions with the name in the field.
      For multiple words with spaces, you need to replace the spaces with undelines such as Company_Name.
      And bookmark name can't contain any of the special characters such as / \ : * ? " < > |
      Thanks for your comment.
  • To post as a guest, your comment is unpublished.
    mary · 5 months ago
    can this be done in older versions of Word or have to be saved as a certain doc type?
  • To post as a guest, your comment is unpublished.
    Ingrid · 5 months ago
    Can you add this to multiple areas on a single page consisting of multiple sections? I was able to successfully complete the process in one section of my document, but when I attempt to complete the same process while on the same page, but in a different section of my document and with new drop down options, only my first added boxes are working, not the ones in the second section..
    • To post as a guest, your comment is unpublished.
      crystal · 4 months ago
      Hi ingrid,
      Supposing you have three groups of dependent drop-down lists in your document. If you need all dependent drop-down lists take effect, please apply the below VBA code and do the below settings:

      In the step 4 and 5 we mentioned in the article, now you need to do the following changes:
      1. For the first group of the dependent drop-down lists, please get into each drop-down list's Properties window and specify the Bookmark as ddfood1 and ddCategory1 separately;
      2. For the second group of the dependent drop-down lists, please get into each drop-down list's Properties window and specify the Bookmark as ddfood2 and ddCategory2 separately;
      2. For the third group of the dependent drop-down lists, please get into each drop-down list's Properties window and specify the Bookmark as ddfood3 and ddCategory3 separately;

      Then go ahead exactly as we provided in the article to finish the whole settings.

      VBA code:
      Sub Populateddfood()
      'Update by Extendoffice 2019/03/18
      Dim xDirection As FormField
      Dim xState As FormField
      Dim xRng As Range
      Dim xFoodBM, xCategoryBM As String
      Set xRng = Selection.Range
      On Error Resume Next
      For i = 1 To ActiveDocument.FormFields.Count
      xFoodBM = "ddfood" & i
      xCategoryBM = "ddCategory" & i
      Set xDirection = ActiveDocument.FormFields(xFoodBM)
      Set xState = ActiveDocument.FormFields(xCategoryBM)
      If (Not (xState Is Nothing)) And (Not (xDirection Is Nothing)) Then
      With xState.DropDown.ListEntries
      .Clear
      Select Case xDirection.Result
      Case "Fruit"
      .Add "Apple"
      .Add "Banana"
      .Add "Peach"
      .Add "Lychee"
      .Add "Watermelon"
      Case "Vegetable"
      .Add "Cabbage"
      .Add "Onion"
      Case "Meat"
      .Add "Pork"
      .Add "Beef"
      .Add "Mutton"
      End Select
      End With
      End If
      Set xDirection = Nothing
      Set xState = Nothing
      Next
      xRng.Select
      End Sub
  • To post as a guest, your comment is unpublished.
    MM · 6 months ago
    Is there a similar code to do the almost the exact same thing except have a text form field automatically populate depending upon the dropdown choice? For example, choosing a specific company in the dropdown and having a text form field automatically populate with the city where the company is located?
    • To post as a guest, your comment is unpublished.
      crystal · 6 months ago
      Good day,
      Sorry can help you with that. Thank you for your comment.