[VBA] Strange problem after you delete a worksheet in the background

Source: Internet
Author: User
Backstage | Problem write a code last night, you will be prepared to a directory in Excel, a worksheet (the same name "Sheet2") bulk delete code as follows, after the successful deletion of the strange problem, was deleted after the processing of Excel files found is nothing, a worksheet is not, but with the VB editor to view, But found that the worksheet is still there, but there is no way to show.

Private Sub CommandButton1_Click ()
Dim app as Excel.Application
Dim xlapp as Variant
Dim Xlworkbooks as workbooks
Dim MyFile, MyPath, myname
MyPath = "D:\temp"
MyName = Dir (MyPath & "\" & "*.xls")
Do While myname <> "" ' Start loop.

Set xlapp = GetObject (MyPath & "\" & MyName)
Set w_sheets = xlapp. Worksheets
xlapp. Application.DisplayAlerts = False ' does not show warning
xlapp. Worksheets ("Sheet2"). Delete
Workbooks (myname). Save
xlapp. Application.DisplayAlerts = True
xlapp. Application.Visible = True
Workbooks (myname). Close
MyName = Dir ' to find the next directory.
Loop
End Sub

Later, and the master to discuss debugging, found that if not GetObject, but directly first use workbook.open can achieve normal.

Application.Workbooks.Open MyName ' This is the key, open the worksheet first
Anyway, why would appear above the situation I also say not clear, but can solve the problem is good ... Oh




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.