2017-08-07 85 views
0

以下代碼是移動工作簿中工作表的函數。它從包含列出工作簿中工作表的列表框的用戶窗體中調用。輸入是一個整數,它給出了移動紙張的方向。工作簿中的左/右在用戶窗體列表框中向上/向下,並且用戶窗體具有向上和向下按鈕,這些按鈕用不同的輸入(向右移動+1和向左移動-2)調用函數。移動工作表時出現不一致的錯誤

如果對象'_Worksheeet'失敗,但該函數有時給出錯誤方法'移動',但不一致。大多數情況下,第二次移動工作表時會出現錯誤,所以我無法多次移動工作表。一旦發生錯誤,我無法再次移動工作表。但是,我可以選擇另一張紙並在發生同樣的事情之前移動一次。

如果我在錯誤處理中實現了一個消息框,則行爲會發生變化。錯誤關閉消息框後,我可以在錯誤發生後再次移動相同的表單。使用消息框,我可以根據需要多次移動工作表,但只能按其他按鈕按下。我猜消息框中斷了代碼執行,出於某種原因,即使是一個給出錯誤的表單,該函數也會再次運行。我嘗試用延遲或自閉信息框替換消息框,但這不會產生相同的結果。

使事情變得更加複雜,有時當我打開用戶窗體應用程序時,移動按鈕完美無缺地工作。我認爲這發生在應用程序打開之前工作表已經打開。

這一切似乎都很不一致,超出了我的理解。任何幫助或建議非常感謝。

Function FlyttMåling(Retning As Integer) As Boolean 

    Application.EnableEvents = False 
    Application.ScreenUpdating = False 

    'code to reference the correct workbook based on outside parameters 
    Dim wb As Workbook, ws As Worksheet 
    FlyttMåling = True 
    If Hovedvindu.LuftlydKnapp.Value = True Then 
     Set wb = ÅpneBok(1) 
    ElseIf Hovedvindu.TrinnlydKnapp.Value = True Then 
     Set wb = ÅpneBok(2) 
    End If 

    'sets variable to the index of sheet to be moved, chosen from list in userform 
    Dim nummer As Integer 
    Set ws = wb.Sheets(1) 
    If Hovedvindu.MålingerFrame.Liste.ListIndex < 0 Then 
     Exit Function 
    Else 
     Set ws = wb.Sheets(Hovedvindu.MålingerFrame.Liste.Value) 
    End If 
    nummer = ws.Index 

    'exit function if trying to move first sheet to the left or last sheet to the right 
    If (Retning = 1 And nummer = wb.Sheets.count) Or (Retning = -2 And nummer = 2) Then 
     Exit Function 
    End If 

    'code that moves worksheet 
    ws.Activate 
    On Error GoTo errHandler: 
errResume: 
    ws.Move after:=wb.Sheets(nummer + Retning) 'THIS LINE CAUSES ERROR 
    On Error GoTo 0 
    Call oppdaterListe 

    'reselect the moved worksheet in the userform list 
    For i = 0 To Hovedvindu.MålingerFrame.Liste.ListCount - 1 
     If ws.Name = Hovedvindu.MålingerFrame.Liste.List(i) Then 
      Hovedvindu.MålingerFrame.Liste.Selected(i) = True 
      Exit For 
     End If 
    Next i 

    Application.EnableEvents = True 
    Application.ScreenUpdating = True 
    Exit Function 

    'error handling just sets the return to false to notify failure to move sheet 
errHandler: 
    FlyttMåling = False 

End Function 
+1

您是否證實此舉實際上有效?你的代碼說「移動工作表,使其位於具有索引(nummer + Retning)的工作表之後」 - 在出現錯誤的情況下,你確定存在包含此特定索引的工作表嗎?它也看起來像你的「退出功能」檢查將不會正確啓動,因爲條件翻轉。 – Vegard

+0

此舉應該是有效的。該索引是從工作簿工作表填充的用戶表單中選擇的。我還通過打印顯示要移動的工作表名稱,索引和名稱的消息框進行了驗證,索引表應該移動到etc以手動驗證它是否嘗試移動正確的工作表。 – ksund

+0

退出檢查應該是正確的。如果「retning」= 1,表格應該向右移動(在索引+ 1之後)。如果工作表已經是最後一個(= sheet.count),則不應該發生這種情況。如果'retning'= -2,表格應該向左移動。如果表索引= 2(Sheet nr 2是第一個數據表,並且是用戶表單中的第一個數據表,Sheet nr 1始終是一個虛擬表單,它不會顯示在用戶表單中,也不應該移動) – ksund

回答

0

找到了解決這個問題的方法。將wb.move更改爲wb.copy,然後刪除舊的工作表並將該副本重命名爲原始工作表的名稱,使此代碼按預期工作。

相關問題