I have a VBA function that will crash excel when I run it ("Microsoft Excel has stopped working"), but works fine if I step through each line in the editor. I want to open another workbook with the function, change the slicers on a given sheet, find a value, and then close the new workbook without saving it. The function I have is as follows:
Function ValueLookup()
Dim Check As Boolean
Dim NewBook As Workbook
Check = IsWorkBookOpen("C:\Location\Filename")
If Check = False Then
Set NewBook = Workbooks.Open("C:\Location\Filename")
Else
Set NewBook = Workbooks("Filename")
End If
NewBook.Activate
Worksheets("Sheetname").Activate
ActiveSheet.PivotTables("pivottable1")ManualUpdate = True
With ActiveWorkbook.SlicerCaches("Slicer_SlicerName")
.ClearManualFilter
.VisibleSlicerItemsList = Array("[Tablename].[Columnname].&[MyValue]")
End With
ActiveSheet.PivotTables("pivottable1").ManualUpdate = False
ValueLookup = ActiveSheet.Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
searchorder:=xlByRows, _
searchdirection:=xlPrevious, _
MatchCase:=False)
If Check = False Then NewBook.Close savechanges:=False
End Function
(IsWorkBookOpen() is taken from Detect whether Excel workbook is already open, and doesn't seem to present any issues).
It seems that trying to close the new workbook is what's causing the issue, and if the workbook is open before I run the function there is no issue. The subroutine that calls the function will normally execute the line after the function right before excel crashes (opening a MsgBox for user input). I have tried adding Sleep 1000 after each line and adding DoEvents after the last line with no change in results. I've tried changing
NewBook.Close savechanges:= False
to
Application.Windows("NewBook").Close
without any difference. I've also tried replacing the end with
If Check = False Then
Cancel = True
Application.OnTime Now, "Close_Xls"
End If
End Function
Sub Close_Xls()
ThisWorkBook.Close savechanges:=False
End Sub
but this closes the wrong workbook (the original one I'd like the macro to be run from) after my subroutine has finished. However, it does seem to execute the code successfully before closing the wrong workbook, and does not cause excel to crash.
Any suggestions?
Edit:
It now appears to work without issues. I changed the following:
If Check = False Then NewBook.Close savechanges:=False
End Function
To
NewBook.Saved = True
If Check = False Then
Cancel = True
Application.OnTime Now, "Close_Xls"
End If
End Function
Sub Close_Xls()
Workbooks("Filename").Close savechanges:=False
End Sub
Thanks!