工作表类的Move方法失败

时间:2018-06-12 14:56:57

标签: excel-vba vba excel

我正在尝试使用下面的在线编码来安排工作簿中的选项卡,但是,在工作簿中安排了一些工作表后,会出现以下错误"运行时错误' 1004&#39 ;;工作表类的Move方法失败。我已经多次遍历宏,它似乎工作正常,直到它遇到一个尚未重命名的工作表。当错误出现时就是这样。发生的行是Sheets(j).Move After:=Sheets(j + 1)

编码如下:

Sub Sort_Active_Book()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
'
'
   iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
     & "Clicking No will sort in Descending Order", _
     vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
   For i = 1 To Sheets.Count
      For j = 1 To Sheets.Count - 1
'
' If the answer is Yes, then sort in ascending order.
'
         If iAnswer = vbYes Then
            If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
               Sheets(j).Move After:=Sheets(j + 1)
            End If
'
' If the answer is No, then sort in descending order.
'
         ElseIf iAnswer = vbNo Then
            If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
               Sheets(j).Move After:=Sheets(j + 1)
            End If
         End If
      Next j
   Next i
End Sub

1 个答案:

答案 0 :(得分:0)

我就是这样做的,但是基于你现有的方法:

Sub Sort_Active_Book()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult

Dim sht1 As Worksheet
Dim sht2 As Worksheet

With ActiveWorkbook

'
'
   iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
     & "Clicking No will sort in Descending Order", _
     vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")

   For i = 1 To .Sheets.Count
      For j = 1 To .Sheets.Count - 1

        Set sht1 = .Sheets(j)
        Set sht2 = .Sheets(j + 1)

        '
        ' If the answer is Yes, then sort in ascending order.
        '
         If iAnswer = vbYes Then
            If UCase$(sht1.Name) > UCase$(sht2.Name) Then
               sht1.Move After:=sht2
            End If
        '
        ' If the answer is No, then sort in descending order.
        '
         ElseIf iAnswer = vbNo Then
            If UCase$(sht1.Name) < UCase$(sht2.Name) Then
               sht1.Move After:=sht2
            End If
         End If
      Next j
   Next i

End With

End Sub

来自评论:使用xlSheetVeryHidden隐藏了其他工作表,因此问题中出现了初始运行时错误。