我需要用户输入来使用vba进行新行

时间:2016-07-22 05:00:54

标签: vba excel-vba excel

所以我有一个代码,其中用户输入一些信息,并将其与表进行比较,如果找到匹配,则将用户信息放入创建的新行中。 我在将信息添加到创建的行时遇到问题。这是我的代码

Sub findData()
    Dim workflow As String
    Dim finalrow As Integer
    Dim i As Integer

    workflow = Sheets("Sheet1").Range("c5").Value
    servergri = Sheets("sheet1").Range("c9").Value
    gridf = Sheets("sheet1").Range("c9").Value
    finalrow = Sheets("Sheet3").Range("c100").End(xlUp).Row

    For i = 5 To finalrow
        If Cells(i, 3) = workflow Then
            If Cells(i, 4) = servergri Then
                Range(Cells(i, 3), Cells(i, 8)).Select
                If ActiveCell.Offset(1).EntireRow.Insert Then
                    'what do I put so that workflow , sergri, gridf, information will go to the new row create?
                ElseIf Cells(i, 5) = gridf Then
                    Range(Cells(i, 3), Cells(i, 8)).Select
                    If ActiveCell.Offset(1).EntireRow.Insert Then
                    Else

                    End If
                End If
            End If
        End If
    Next
End Sub

2 个答案:

答案 0 :(得分:0)

请参阅下面的代码,与您的代码进行比较。这应该做你想要的,但它没有经过测试:

Sub findData()
Dim workflow As String
Dim finalrow As Integer
Dim i As Integer

workflow = Sheets("Sheet1").Range("c5").Value
servergri = Sheets("sheet1").Range("c9").Value
gridf = Sheets("sheet1").Range("c9").Value
finalrow = Sheets("Sheet3").Range("c100").End(xlUp).Row

For i = 5 To finalrow
    If Cells(i, 3) = workflow Then
        If Cells(i, 4) = servergri Then
            ActiveCell.Offset(1).EntireRow.Insert
            Range(Cells(i, 3), Cells(i, 8)).Copy
            Range(Cells((i+1),3)).PasteSpecial xlPasteValues
        ElseIf Cells(i, 5) = gridf Then
            ActiveCell.Offset(1).EntireRow.Insert
            Range(Cells(i, 3), Cells(i, 8)).Copy
            Range(Cells((i+1),3)).PasteSpecial xlPasteValues 
        End If
    End If
Next i
End Sub

答案 1 :(得分:0)

让我们从这里开始吧。显然,如果条件符合用户的输入,则表示在Sheets(" Sheet3")中循环遍历行,以寻找插入行。

我将所有的if语句合并为一个,完全限定了Sheet3上单元格的引用,并添加了一些示例代码来演示如何将数据添加到新行。

Sub findData()
    Dim workflow As String
    Dim finalrow As Integer
    Dim i As Integer

    With Sheets("Sheet1")
        workflow = .Range("C5").Value
        servergri = .Range("C9").Value
        gridf = .Range("C9").Value
    End With

    With Sheets("Sheet3")
        finalrow = .Range("C" & Rows.Count).End(xlUp).Row

        For i = 5 To finalrow
            If .Cells(i, 3) = workflow And (.Cells(i, 4) = servergri Or .Cells(i, 5) = gridf) Then

                .Rows(i).Insert
                'Add new information to the new row.  
                'The new row number is still = i

                .Cells(i, 1) = "???"
                .Cells(i, 2) = "???"
                .Cells(i, 3) = "???"
                .Cells(i, 4) = "???"

                'If you only want to add one row then your should exit the loop
                Exit For
            End If
        Next
    End With
End Sub

这有帮助吗?你需要澄清吗?