在排序时陷入运行模式

时间:2015-11-28 20:55:08

标签: excel vba excel-vba runtime runtime-error

我正在尝试通过字符串sby中的文本将sheet 2上的数据排序到sheet 9

我认为逻辑从下面的代码很简单。

但是下面的代码给出了

  

运行时错误1004;为行wk.Rows(j).EntireRow.Select

选择范围等级方法失败

更新1:

  

我现在没有收到错误但是它已经停留在[running]模式很长一段时间我不得不打破代码执行。我正在尝试实现下面的I / O逻辑。我认为我的代码应该可以工作,但它要么花很长时间,要么陷入无限循环。你能帮忙吗

输入:

col B
Commercial
Tech
Operation
Commercial
Commercial
.
.
.
. 

输出:

col B
Commercial
Commercial
Commercial
Tech
Operation
.
.
.

代码

Option Explicit

Sub SortByCommercial()
Dim wk As Worksheet
Dim sby, FinalRow, i, j, p
Dim WsCount As Integer
WsCount = ActiveWorkbook.Worksheets.Count
Dim wb As Workbook
Set wb = ActiveWorkbook

sby = "Commercial"

For i = 2 To WsCount

Set wk = Sheets(i)
FinalRow = wk.Range("A900000").End(xlUp).Row
p = FinalRow + 1

    For j = 2 To FinalRow
        If Trim(wk.Range("B" & j).Text) <> sby Then

            wk.Rows(j).EntireRow.Select
            Selection.Cut

            wk.Range("A" & p).Select
            wk.Paste

            Rows(j).EntireRow.Select
            Selection.Delete Shift:=xlUp

            Range("A1").Select

        Application.CutCopyMode = False
            j = j - 1
        Else: End If
    Next j

Next i


End Sub

1 个答案:

答案 0 :(得分:1)

Sub SortByCommercial()
Dim wk As Worksheet
Dim sby, FinalRow, i, j, p
Dim WsCount As Integer
WsCount = ActiveWorkbook.Worksheets.Count
Dim wb As Workbook
Dim lngRowTemp as Long
Set wb = ActiveWorkbook

sby = "Commercial"

For i = 2 To WsCount

    Set wk = Sheets(i)
    Sheets(i).Activate        

    For j = 2 To FinalRow
        FinalRow = wk.Range("A900000").End(xlUp).Row + 1
        lngRowTemp = FinalRow -1

        If Trim(wk.Range("B" & j).Text) <> sby Then
            wk.Rows(j).EntireRow.Select
            Selection.Cut
            wk.Range("A" & FinalRow).Select
            wk.Paste
            Application.CutCopyMode = False
        End If
    Next j

    for j = lngRowTemp to 2 step -1
        if cells("B" & j).value = "" then
            cells("B" & j).EntireRow.Delete
        end if
    next j
Next i
End Sub