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