宏以连续的每月日期将数据复制到更多行中

时间:2018-10-04 00:45:59

标签: excel-vba

我使用一个宏表格,其中写出每月X次收到的金额 An example of how I want it to be

如何根据我注册的时间制作一个宏,该宏将在下个月继续填充新行 这是我现在的代码,无需添加更多行

Private Sub CommandButton1_Click()
Dim lRow As Long
    Dim ws As Worksheet
    Set ws = Worksheets("sheets")
    lRow = ws.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0).Row
    With ws
        .Cells(lRow, 1).Value = ""
        .Cells(lRow, 2).Value = Me.TextBox1.Value
        .Cells(lRow, 3).Value = Me.TextBox2.Value
        .Cells(lRow, 4).Value = Me.TextBox3.Value
End With
    Unload Me
End Sub

(注意:这会添加新行,而不是以现有行为代价)

如果有任何帮助,想法,意图,我将很高兴

编辑: 更清楚我想要的内容

如果我用9号表格和500 $书写,则将添加9行,金额为500 $,但每月日期会增加

我不是宏观专家

e

1 个答案:

答案 0 :(得分:0)

您将要验证输入。如果用户将al;kjfdadsk放入任何文本框怎么办?您需要确保输入符合期望。

像这样限制输入:

Me.TextBox1 = Number
Me.TextBox2 = Date
Me.TextBox1 = Number

您也可以对此进行修改,以确保Amount为非负数。或者,也许您想在Amount上设置一个最大值?无论哪种方式,都值得考虑要在这里放置然后构建它们的限制。我在上面为您添加了3个限制。


Private Sub CommandButton1_Click()

'Validate entries    
If Not IsNumeric(Me.TextBox1) Then
    MsgBox "Invalid Amount Entry"
ElseIf Not IsDate(Me.TextBox2) Then
    MsgBox "Invalid Date Entry"
ElseIf Not IsNumeric(Me.TextBox3) Then
    MsgBox "Invalid Payment Entry"
End If

'Rest of code goes here and will be ran once the above entries are validated
Dim ws As Worksheet, LRow as Long, i as Integer
Set ws = Worksheets("sheets")

LRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Offset(1, 0).Row

ws.Range("A" & LRow) = Me.TextBox2
ws.Range(ws.Cells(LRow, 2), ws.Cells(LRow + Me.TextBox1, 2)) = Me.TextBox3

For i = (LRow + 1) To (LRow + Me.TextBox1 - 1)
    ws.Range("A" & i ) = DateAdd("m", 1, ws.Range("A" & i -1)
Next i

Unload Me

End Sub