如何在将值添加到下一个可用行之前循环值的范围

时间:2019-04-15 20:21:46

标签: vba loops range

我正在设置一个按钮,以检查值的范围(如果该值不存在),然后将值复制到下一个可用行

Private Sub CommandButton2_Click()
    Dim LrowCompleted As String
    If TextBox1.Text = "" Then
        MsgBox "DON'T DO THAT"
    Else
        LrowCompleted = Sheets("Budget").range("N4").End(xlDown).Row
        Sheets("Budget").range("N" & LrowCompleted + 1) = TextBox1.Text
        Unload Me
        MechanicalEquipment.Show
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

首先。 LrowCompleted应该是Long而不是String。

第二。您需要构建“查找”部分。您是否只会在单个列中找到该值?下面的例子。未经测试,但应该可以。

Private Sub CommandButton2_Click()
    Dim LrowCompleted As Long, fText as String, Dim findValue As Range
    fText = TextBox1.Text
    'You probably dont need to check all 3 below but I'm not on excel to check the best one to use.
    If fText = "" Or fText = Nothing Or fText = Null Then
        MsgBox "Provide what to look for"
    Else
        Set findValue = Sheets("Budget").Columns("N:N").Find(fText, Range("N1"), xlValues, xlPart, xlByColumns, xlNext)
        If findValue Is Nothing Then
            'Nothing found lets place it at the end
            LrowCompleted = Sheets("Budget").Range("N4").End(xlUp).Row + 1
            Sheets("Budget").Range("N" & LrowCompleted) = fText
            Unload Me
            MechanicalEquipment.Show
        Else
            'I found something, do nothing i guess
        End If
    End If
End Sub