Excel 复制后如何关闭源文件?
将原始源文件复制到仪表板后,我正在尝试关闭它。我该怎么做Excel 复制后如何关闭源文件?,excel,vba,Excel,Vba,将原始源文件复制到仪表板后,我正在尝试关闭它。我该怎么做 Sub Load_Loan() Dim fNameAndPath As Variant fNameAndPath = Application.GetOpenFilename(FileFilter:="*.XLS, *CSV", Title:="Select Tape") If fNameAndPath = False Then Exit Sub Workbooks.Open Filename:=fN
Sub Load_Loan()
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="*.XLS, *CSV", Title:="Select Tape")
If fNameAndPath = False Then Exit Sub
Workbooks.Open Filename:=fNameAndPath
ActiveSheet.Copy After:=Workbooks(" Dashboard.xlsm").Sheets(Workbooks(" Dashboard.xlsm").Worksheets.Count)
ActiveWorkbook.Close
Workbooks(" Dashboard.xlsm").Activate
我必须调试如果使用对象变量,会更安全:
dim wb as workbook
set wb = Workbooks.Open(Filename:=fNameAndPath)
'do your stuff
wb.close
使用对象变量更安全:
dim wb as workbook
set wb = Workbooks.Open(Filename:=fNameAndPath)
'do your stuff
wb.close
您需要更精确地确定工作表所在的工作簿,并尽可能避免使用
ActiveSheet
和ActiveWorkbook
Public Sub Load_Loan()
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="*.XLS, *CSV", Title:="Select Tape")
If fNameAndPath = False Then Exit Sub
Dim WbSource As Workbook 'reference the opened workbook in a variable that we can use later to access/close it
Set WbSource = Workbooks.Open(Filename:=fNameAndPath)
Dim WbDestination As Workbook
Set WbDestination = ThisWorkbook 'or if it is not the workbook this code is in then Workbooks("Dashboard.xlsm")
'specify a worksheet in the source workbook
WbSource.Worksheets(1).Copy After:=WbDestination WbDestination.Sheets(WbDestination.Sheets.Count)
WbSource.Close SaveChanges:=False 'close and don't save
End Sub
您需要更精确地确定工作表所在的工作簿,并尽可能避免使用
ActiveSheet
和ActiveWorkbook
Public Sub Load_Loan()
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="*.XLS, *CSV", Title:="Select Tape")
If fNameAndPath = False Then Exit Sub
Dim WbSource As Workbook 'reference the opened workbook in a variable that we can use later to access/close it
Set WbSource = Workbooks.Open(Filename:=fNameAndPath)
Dim WbDestination As Workbook
Set WbDestination = ThisWorkbook 'or if it is not the workbook this code is in then Workbooks("Dashboard.xlsm")
'specify a worksheet in the source workbook
WbSource.Worksheets(1).Copy After:=WbDestination WbDestination.Sheets(WbDestination.Sheets.Count)
WbSource.Close SaveChanges:=False 'close and don't save
End Sub
不要使用
Workbooks.Open文件名:=fNameAndPath
而应将sourceWB设置为工作簿
和设置sourceWB=Workbooks.Open(文件名:=fNameAndPath)
。然后,在您的过程结束时,您只需执行sourceWB.Close
而不是Workbooks.Open Filename:=fNameAndPath
您应该将sourceWB设置为工作簿
和设置sourceWB=Workbooks.Open(Filename:=fNameAndPath)
。然后,在过程结束时,只需执行sourceWB.Close