[英]Excel VBA will not close my opened workbook
I am pretty much new to VBA and have been trying to learn, with this I have created a code that opens another work book and combines all data to a database file and then copy this to my current open file, the problem I have is that it will not close the workbook and takes a long time doing so.我对 VBA 非常陌生并且一直在努力学习,我创建了一个代码,可以打开另一个工作簿并将所有数据合并到一个数据库文件中,然后将其复制到我当前打开的文件中,我遇到的问题是它不会关闭工作簿,并且需要很长时间才能关闭。 Any ideas please?.请问有什么想法吗?
'''
Option Explicit
Sub GasStockReport()
Dim wb As String
Dim st As String
Dim path As String
path = "C:\Users\si2066\OneDrive - ENGIE\Desktop\MP Templates\MP - Stock Control\"
wb = "Gas Stock Take v2"
Workbooks.Open path & wb
Dim sh As Worksheet
Dim destsh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Database").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Set destsh = ActiveWorkbook.Worksheets.Add
destsh.Name = "Database"
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> destsh.Name Then
Last = GetLastRow(destsh, 1)
With sh
Set CopyRng = sh.Range("A2:K" & GetLastRow(sh, 1))
End With
If Last + CopyRng.Rows.Count > destsh.Rows.Count Then
MsgBox "There are not enough rows in the Destsh"
GoTo ExitTheSub
Else
CopyRng.Copy IIf(Last = 1, destsh.Cells(1, "b"), destsh.Cells(Last + 1, "b"))
End If
If Last = 1 Then
destsh.Cells(Last, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
Else
destsh.Cells(Last + 1, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
End If
End If
Next
ExitTheSub:
Application.Goto destsh.Cells(1)
destsh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Range("A1").Select
Range(Selection, ActiveCell.End(xlDown).End(xlToRight)).Select
Selection.Copy
ActiveWindow.SelectedSheets.Visible = False
ThisWorkbook.Sheets("Stock History").Activate
Range("N1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.DisplayAlerts = False
On Error Resume Next
Workbooks("Gas Stock Take v2").Close SaveChanges:=True
On Error GoTo 0
Application.DisplayAlerts = True
ThisWorkbook.Sheets("Stock Take").Activate
Call Click
End Sub
Public Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1)
As Long
With ws
GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
End With
End Function
'''
Your error handling is fine.您的错误处理很好。 Using On Error GoTo 0
turns off On Error Resume Next
.使用On Error GoTo 0
关闭On Error Resume Next
。
I think the issue is the amount of data you're leaving on the clipboard after copy and paste.我认为问题在于复制和粘贴后您在剪贴板上留下的数据量。 If you use .copy
and .paste
always follow that up with Application.CutCopyMode = False
如果您使用.copy
和.paste
,请始终使用Application.CutCopyMode = False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.