Como posso adicionar a lista suspensa após inserir uma nova linha no VBA


0

Estou tentando inserir uma lista suspensa com dois itens depois de adicionar uma nova linha. Este código abaixo não está funcionando corretamente.

     Dim varUserInput As Variant
     varUserInput = InputBox("Enter Row Number where you want to add a row:", 
    "What Row?")
    If varUserInput = "" Then Exit Sub
    RowNum = varUserInput
    Rows(RowNum + 1).Insert Shift:=xlDown
    With Sheet1.RowNum.listBox1
     .AddItem "Paris"
     .AddItem "New York"
    End With

Não sei exatamente o que você está tentando fazer aqui. Será que ListBox1já existem ou que você está tentando adicioná-lo? Além disso, RowNumé uma string - para obter uma Rangereferência que você precisa Sheet1.Rows(RowNum).
— Comintern

@Comintern - Estou tentando adicionar o Listbox automaticamente à nova linha ..
— user3713336 1/17/17

@Comintern Dropdownlist
— user3713336

Respostas:


0

Tente o seguinte:

Sub Macro1()

RowNum = InputBox("Enter Row Number where you want to add a row:", "What Row?")
If RowNum = "" Then Exit Sub

Range("A1").Offset(RowNum, 0).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="London,Sydney"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With
End Sub

Nota: gravei a maior parte disso usando a ferramenta Gravar macro na guia Desenvolvedor e, em seguida, editei para usar partes do seu código. É um método útil quando você não tem certeza do código exato necessário para inserir algo, como esta lista suspensa de validação.

Editar: para adicionar duas listas ao mesmo tempo:

Sub Macro1()
'ask user for row to insert data
RowNum = InputBox("Enter Row Number where you want to add a row:", "What Row?")
If RowNum = "" Then Exit Sub

'insert dropdowns in column A
Range("A1").Offset(RowNum, 0).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="London,Sydney"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

'inset second drop down in column E
Range("E1").Offset(RowNum, 0).Select '<-- change reference to E
'Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove '<-- line removed as don't need to insert twice

With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="New York,Jakarta"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

End Sub

e com muitas listas idênticas:

Sub Macro1()
Dim RowNum As Integer
Dim Lists As Integer

'ask user for row to insert data
RowNum = InputBox("Enter Row Number where you want to add a row:", "What Row?")

'insert row
Range("A1").Offset(RowNum, 0).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

'ask how many drop down lists to make
Lists = InputBox("Enter number of drop down lists to make in this row:", "Number?")

i = 0

Do While i < Lists And i < 1000
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="Hong Kong,Rome,Wellington,Cairo"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

    'move across one cell
    ActiveCell.Offset(0, 1).Range("A1").Select

    i = i + 1
Loop


End Sub

Isto não está funcionando, não é capaz de inserir toda linha e não é capaz de adicionar 2 lista suspensa usando este método
— user3713336

desculpe, eu nunca usei um livro. Apenas 15 anos tentando e pesquisando código na internet quando não tenho certeza. Eu recomendo jogar com a função Record Macro e ver o que ela produz - com e sem as Referências relativas ativadas. E aprenda como os loops funcionam. Depois de criar código com iteração, você pode criar macros úteis que removem a repetição.
— Sir Adelaide

Não funciona quando tento adicionar duas na lista suspensa .... estou fazendo algo errado ... Altero um pouco --Range ("A1", "E1"). Offset (RowNum, 0) .Select
— user3713336

A função Range usa apenas uma referência de célula como entrada; você não pode atribuir "A1" e "E1" ao mesmo tempo. Vou mostrar um exemplo para duas listas suspensas.
— Sir Adelaide

Adeladie --- uau, você é a melhor .... o que posso fazer ou como posso me aperfeiçoar para ser um programador como você ... por favor, me dê algumas dicas ou livros. ou você tem tutorial no youtube ....
— user3713336
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.