Excel Workbook_BeforeClose函数使其他工作簿崩溃

ubby3x7f  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(215)

我在下面写了一个小函数来保存一些数据,每当我关闭这个电子表格。但如果我有多个电子表格打开,Excel将崩溃,一旦我关闭一个与"Workbook_BeforeClose"函数。有人见过类似的问题吗?谢谢!
下面是我的代码:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

Dim wb As Workbook
Dim sht1 As Worksheet
Dim current_sht1 As Worksheet
Dim FilePath As String
Dim shtName1 As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False

FilePath = "C:\Users\DLW\Test1\Local_datafile.xlsx"
shtName1 = "Tab1"

Set current_sht1 = ThisWorkbook.Worksheets(shtName1)

Set wb = Application.Workbooks.Open(FilePath)
Set sht1 = wb.Worksheets(shtName1)

sht1.Cells.Clear

current_sht1.UsedRange.Copy
sht1.Range("A1").PasteSpecial xlPasteValues

Application.CutCopyMode = False

wb.Close SaveChanges:=True
Application.ScreenUpdating = True

 ThisWorkbook.Save
MsgBox "Saved to local file."

End Sub
owfi6suc

owfi6suc1#

“FilePath”不是实际路径,它只是要打开的工作簿的名称。要打开已关闭的工作簿,需要实际路径,如
“C:\用户\DLW\测试1\本地数据文件. xlsx”
如果它与ThisWorkbook位于同一文件夹中,则可以使用

FilePath = ThisWorkbook.Path & "\Local_datafile.xlsx"

相关问题