gpt4 book ai didi

excel - 使用 VBA 在多行中插入验证列表

转载 作者:行者123 更新时间:2023-12-04 22:19:38 25 4
gpt4 key购买 nike

我正在制作一个电子表格来控制我办公室的财务状况。我制作了一个 VBA 代码,在其中输入了 4 个不同的数据: i) 客户名称; ii) 契约(Contract)总值(value); iii) 支付契约(Contract)的月数; iv) 第一次付款的日期。
根据付款的月数 (iii),代码插入相同数量的行。在@Paster (link to question) 的帮助下,我能够做到这一点。
现在我有一个新问题:在每个新行中,我希望在第 6 列有一个验证列表(是/否),我可以在其中控制是否付款。当只添加 1 行时,我能够做到这一点,但是当“If .Cells(iRow, 5) > 1 Then”启动时我不知道如何添加。
我希望它看起来像这样:


客户
值(value)
日期
控制


约翰
100
2020 年 1 月 1 日
是/否

约翰
100
2020 年 2 月 1 日
是/否

克莱尔
500
2020 年 1 月 5 日
是/否


我还在学习 VBA,我只是想不通。
实际代码是:

Private Sub cmdAdd_Click()

Dim iRow As Long
Dim ws As Worksheet
Dim Name As String
Dim counter As Integer
Dim money As Double
Dim Data As Date
Dim i As Integer

Set ws = Worksheets("Projetos")

'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

'copy the data to the database
With ws
.Cells(iRow, 2).Value = Me.boxCliente.Value 'Client info
.Cells(iRow, 3) = CCur(boxValor.Value) 'Value
.Cells(iRow, 5).Value = Me.boxParcela.Value '# of payments
.Cells(iRow, 4) = CDate(boxData.Value) 'Date

'add validation list to row
With Cells(iRow, 6).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="Não,Sim"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Cells(iRow, 6).Value = "Não"

'if multiple payments, then
If .Cells(iRow, 5) > 1 Then
Name = .Cells(iRow, 2).Value
counter = .Cells(iRow, 5).Value
money = .Cells(iRow, 3).Value
Data = .Cells(iRow, 4).Value

For i = 0 To counter - 1
.Cells(iRow + i, 2).Value = Name
.Cells(iRow + i, 3).Value = money / counter
.Cells(iRow + i, 4).Value = Format(DateAdd("m", i, Data), "mm/dd/yyyy")
Next i
End If
End With

'clear the data
Me.boxCliente.Value = ""
Me.boxValor.Value = ""
Me.boxParcela.Value = ""
Me.boxData.Value = ""

End Sub

最佳答案

采用与一行相同的验证逻辑,并将其包含在将值复制到每一行的循环中( For i = 1 to counter - 1 )

For i = 0 To counter - 1
.Cells(iRow + i, 2).Value = Name
.Cells(iRow + i, 3).Value = money / counter
.Cells(iRow + i, 4).Value = Format(DateAdd("m", i, Data), "mm/dd/yyyy")

'add validation list to row
With Cells(iRow, 6).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="Não,Sim"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Cells(iRow, 6).Value = "Não"
Next i

关于excel - 使用 VBA 在多行中插入验证列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65306696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com