2016-04-15 67 views
0

我試圖弄清楚這一點。在我的主要部分中,我稱之爲函數。不知何故,它結束了我在該函數結束時的運行。它顯示「結束前」,從不顯示「我發現了」有人知道問題是什麼嗎?VBA函數永遠不會返回主Sub

Sub Main() 
     call CopyAndDelete() 
     msgbox "I made it out" 
End Sub 

Function CopyAndDelete() 
Dim CopyFromWB As Workbook 
Dim CopyToWB As Workbook 
Dim wb As Workbook 
Dim CopyThisWS As Worksheet 
Dim ws As Worksheet 
Dim Path As String 
Dim FileName As String 

Application.DisplayAlerts = False 

Set CopyToWB = Workbooks("test.xlsm") 
CopyToWB.Activate 

For Each ws In ActiveWorkbook.Sheets 
    Select Case ws.Name 
     Case "A" 
      ws.Delete 
     Case "B" 
      ws.Delete 
     Case "C" 
      ws.Delete 
     Case "D" 
      ws.Delete 
    End Select 
Next ws 

Path = Application.GetOpenFilename(Title:="choose a file") 
FileName = Right(Path, Len(Path) - InStrRev(Path, "\")) 
For Each wb In Workbooks 
    If wb.Name = FileName Then 
     Workbooks(FileName).Close 
    End If 
Next wb 

Set CopyFromWB = Workbooks.Open(Path) 
Set CopyThisWS = CopyFromWB.Worksheets(1) 
CopyThisWS.Copy After:=CopyToWB.Worksheets(1) 
ActiveSheet.Name = "New A" 
CopyFromWB.Close 

Application.DisplayAlerts = True 

MsgBox "Before end" 

End Function 
+2

它的模式,所以它實際上是一個破發點。因此,在「我完成」之前,必須在「Before end」消息上點擊「OK」才能執行。清除第一個對話框後,它應該繼續運行。 –

+0

我實際上點擊確定按鈕,這是運行結束。就像我說的「我做到了」永遠不會在屏幕上顯示 –

+0

嘗試使它成爲一個'Sub'而不是'function' – Davesexcel

回答

1

這工作:

Sub Main() 
    Call CopyAndDelete 
    MsgBox "I made it out" 
End Sub 

Function CopyAndDelete() 
    MsgBox "Before end" 
End Function 

因此,也許你關閉你在當你調用的宏工作表?宏應該被添加到一個模塊,也許它需要在一個模塊中以聲明爲public的函數的Normal模板:

Sub Main() 
    Call CopyAndDelete 
    MsgBox "I made it out" 
End Sub 

Public Function CopyAndDelete() 
    ... your rest of the code ... 
    MsgBox "Before end" 
End Function 

H個,

相關問題