根据输入框中的输入值移动行

时间:2015-01-07 02:24:12

标签: excel excel-vba vba

我需要一些帮助。我尝试做的是根据输入框中的用户输入移动一行。但是我收到了无效限定符错误。帮帮我,谢谢!突出显示的错误是lSource行。

Sub MoveRow()

       Dim lDestRow   As Long
       Dim lSourceRow As String
       Dim zMsg       As String

       lSourceRow = InputBox("Please Enter the row you want to move")
       zMsg = "Move Row " & Format(lSourceRow.Row) & " to Row?" & _
              vbCrLf & "Enter 0 to Exit"

       lDestRow = InputBox(zMsg, "Move Entire Row", 0)
       If lDestRow <> 0 And lDestRow <> lSourceRow Then

         ActiveCell.EntireRow.Select
         Selection.Cut
         Rows(lDestRow).Select
         Selection.Insert Shift:=xlDown

       Else

         If lDestRow <> 0 Then

           MsgBox "Source Row and Destination Row" & vbCrLf & _
                  "are the same -NO Action Taken-", _
                  vbOKOnly + vbInformation, _
                  "Invalid Row Move Request"

         End If

       End If

End Sub

1 个答案:

答案 0 :(得分:0)

不完全确定您想要实现的目标。但你可以尝试一下。

With ActiveSheet 'Replace to suit - e.g. Sheets("Sheet1")
    Dim lSourceRow As Long
    Dim lDestRow As Long
    Dim zMsg As String

    lSourceRow = InputBox("Please Enter the row you want to move.")
    zMsg = "Move Row " & Format(lSourceRow) & " to what Row?" & _
          vbCrLf & "Enter 0 to Exit"

    lDestRow = InputBox(zMsg, "Move Entire Row", 0)

    If lDestRow <> 0 And lSourceRow <> 0 Then
        If lDestRow <> lSourceRow Then
            .Rows(lSourceRow).Cut
            .Rows(lDestRow + IIf(lDestRow = 1, 0, 1)).Insert xlDown
        Else
            MsgBox "Source Row and Destination Row" & vbCrLf & _
                "are the same -NO Action Taken-", _
                vbOKOnly + vbInformation, _
                "Invalid Row Move Request."
        End If
    End If
End With

这是最简单的形式。你想要做的事情必须包括对输入的大量测试 就像测试它是否为负数,不是字符串或小数或者用户按取消关闭。 这只是你开始的事情。我把剩下的留给你了。
这实际上将行移动到目标行的上一个位置。 HTH。