VBA函数永远不会返回主Sub

时间:2016-04-15 16:39:21

标签: vba excel-vba excel

我想弄明白这一点。在我的主要子中,我调用一个函数。不知何故,它结束了我在该功能结束时的运行。它显示“结束前”并且从不显示“我已经完成”有人知道问题是什么吗?

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

1 个答案:

答案 0 :(得分:1)

这有效:

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

Function CopyAndDelete()
  MsgBox "Before end"
End Function

所以也许你正在关闭调用宏时的工作表?宏应该添加到模块中,也许它需要在Normal模板的Module中,并且函数声明为public:

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个,