How do I delete VBA code from a sheet using VBA? - vba

I want to delete the VBA code contained within a sheet through VBA. Currently, I have a code that copies a sheet across to a new workbook and deletes all images from it. However, these images are set to do things on Worksheet_Activate in the code, which then causes an error whenever I flick to that sheet with no images there.
I know I can get rid of modules etc using something along the lines of:
With ActiveWorkbook.VBProject
For x = .VBComponents.Count To 1 Step -1
.VBComponents.Remove .VBComponents(x)
Next x
For x = .VBComponents.Count To 1 Step -1
.VBComponents(x).CodeModule.DeleteLines _
1, .VBComponents(x).CodeModule.CountOfLines
Next x
End With
but that does not delete from the sheet (or the workbook for that matter. Would be interesting to know if that was possible too).
The code itself will need to be valid for Excel versions 2003 through to 2013 (so cannot use the save as xlsx workaround).

Found out the issue. My code works fine, just the computer I was testing it on did not allow access to the VBA project object model (and was running it with an On Error Resume Next earlier on in the code)
Will have to write an exception in to sort that out in such cases.
Thanks to #mehow #nixda #SiddharthRout and #DaveU for the help

Related

Mystery Excel Worksheet Objects added by VBA

I have been creating a .xlsm Workbook that contains various bits of VBA. It simply copies data from two other workbooks into tables and then refreshes the PivotTables that are based on those tables to update the charts on the main workbook. All things I have done before in different workbooks without issue. Whilst working on the workbook I have naturally open, saved, and then closed the workbook several time over several different days.
Typically, now that I believe the workbook to be finished, it has developed a glitch whilst opening. Initially I was unable to open the file at all, as it would immediately crash. Only by saving the file to onedrive and downloading it back again, have I been able to keep the file open to see what is going on (for some reason this worked, I don't know why!).
I immediately suspected something in the VBA and so one press of Alt+F11 later I was confronted with this (image above).
All of the Blue Excel Objects in this picture were not created by me!
They contain no code and I do not seem to be able to open them as regular Excel Worksheets.
My Questions are,
does anyone have any idea what may be causing this?
Has anyone even seen this before?
Where do I start debugging this?
Attempting to run any of the VBA in the workbook causes it to instantly crash.
The VBA i suspect the most for the crashing is in these sections;
Public Function ThisWorkbookPath()
ThisWorkbookPath = ThisWorkbook.Path & Application.PathSeparator
End Function
which is passed to;
Public Function CheckPath(ByVal PathString As String) As Boolean
Application.Volatile (True)
If Strings.Right(PathString, 1) = "\" Then
CheckType = vbDirectory
Else
CheckType = vbNormal
End If
If Len(Dir(PathString, CheckType)) > 0 Then
CheckPath = True
Else
CheckPath = False
End If
End Function
These are both used in the workbook as user defined functions to check if the folder that contains the other 2 workbooks exists on the computer before trying to open them.
ThisWorkbook is now ThisWorkbook1 which might explain why, as the forumla in the workbook calculates, it can't find the correct path and just crashes.
But this doesn't explain where these extra objects came from in the first place.
Any help would be gratefully appreciated
I just had the same issue with Office365, made a code review and found out that I was using the same name for a public constant and a parameter to a function. After renaming the parameter and rerunning the macro, it did not happen again.

Copy from a workbook to another workbook

I am having issues developing this code. I was able to develop the code to copy new data from my workbook to an existing path but am running into issues when trying to retrieve data from the existing path work book.
The concept is that there is a workbook in my system that will be collecting data. The data comes from different users that are working on project information. Once they have completed the project this new information along with existing information gets uploaded back to the workbook collecting that data. The work book collecting the data will always have a defined path. The workbooks that users are working off of will be in multiple places across the system.
The below macro keeps failing on the "Organizer.Sheets("Partnumber_Vendor_Database").Select". I am unsure why.
"Organizer" is the local database the user will use.
"Partnumber_Vendor_File" is the local database the information is stored.
If you can see that this code could be developed better please let me know! :)
Sub Find_Partnumber_Vendor_File()
' This sub is to open the partnumber_Vendor file to update the local database.
On Error Resume Next
Dim Organizer As Workbook
Set Organizer = Application.ActiveWorkbook
Dim Partnumber_Vendor_File As Workbook
Set Partnumber_Vendor_File = Workbooks.Open("S:\Supply Chain\PURCHASING\Forms and Templates\BOM Organizer\Partnumber_Vendor_File.xlsx")
If Err.Number = 1004 Then
MsgBox "Could not open. Check path in VBA"
Exit Sub
End If
If Partnumber_Vendor_File.ReadOnly Then
MsgBox "Sorry, partnumber to vendor database was already in use, try later"
Exit Sub
End If
On Error GoTo 0
Dim Data As Long
Data = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row
Range("A1:" & "D" & Data).Copy
Organizer.Sheets("Partnumber_Vendor_Database").Select
Range("A1:D1").Select
Selection.Insert Shift:=xlDown
Partnumber_Vendor_File.Close
End Sub
Althoug it is easy to use, avoid ActiveWorkbook, ActiveSheet and Sheets(<Title of the Sheet.).
The problem with the first two is that is hard to tell if the activeworkbook is actually the workbook you are looking for, specially when there are more than 1 workbook open. To workaround this, one solution is the use the Workbooks object to select the correct work book by its NAME (property CodeName). The Same for the Sheets, change the REAL NAMES of the Sheets so you can properlly call them.
The third is basically the same principle. In general, do not use titles of Sheets as references, use the REAL NAME of the object. Use the Property window in the VBA code to change that.
The error may come from 2 situations:
1 - Your selected workbook is not the actual workbook you want to work on.
2 - The Sheet "Partnumber_Vendor_Database" had its title changed or miswritten.
Hope it helps.

Run-Time error '32809': Application-defined or object-defined error

All,
I just upgraded to Excel 2013 and am running into a strange issue. I have a macro-enabled workbook that has worked successfully for quite some time now. I was updating some of the code and came across this error (32809) when trying to write to a specific sheet. In troubleshooting, I tried this.
Sheets("Summary").Range("G8").Value = "Test"
This resulted in the same error. Then I tried this.
Debug.Print ActiveSheet.Name
Same error. So I selected another sheet on the workbook and debug.print on the name. Worked fine.
Then I tried this.
Debug.Print Sheets(2).Name (This is the sheet number of the problemic sheet)
Same error. It seems to me that there is some form of corruption with this sheet but I am reticent about deleting and recreating. Any suggestions?
Thanks!
While it wasn't a perfect solution, here is how I finally resolved it. I had a user that was still on Excel 2010 make a copy the corrupt sheet within the same workbook, delete the corrupt sheet, then rename the new sheet to the original name. I was then able to use the workbook in Excel 2013 without issue.
I have a Workbook Open Macro which counts the number of rows in a table on opening so that I can summarize how many records were added or deleted during the data entry session:
Private Sub Workbook_Open()
Dim TotalRows As Integer
TotalRows = Worksheets("Data").ListObjects(1).ListRows.Count
If Range("LastRecordOnStart") <> TotalRows Then Range("LastRecordOnStart") = TotalRows
' Stop
End Sub
I started getting the run-time error '32809' with the following line in the code above highlighted in the debugger every time I opened the workbook...
TotalRows = Worksheets("Data").ListObjects(1).ListRows.Count
Rebooting or opening the workbook on another PC still would not fix it. Even opening a previously saved working copy would give the same error - strange. Note:
While coding, I will periodically save the workbook and use windows explorer to copy a snapshot of the workbook where it creates myworkbook copy(1).xlsm, copy(2).xlsm, etc and if I get a corrupted workbook, I rename it myworkbook.bad.xlsm and rename the latest saved working version (e.g myworkbook copy(6).xlsm to MyWorkbook.xlsm with minimal loss.
When this run-time error occurs though, I've had to rebuild the book several times. It only appears to happen when the workbook crashes after a long session of debugging new code with the Userform open and I have to close excel from the Task Manager.
I read the posts here today and was convinced that it was page related when I could list the listrows count on another sheet and if I converted the Listobject on the "Data" worksheet back to a range and recreated the table, I'd still get the run-time error. To cut a long story short, I tried the following:
Open the workbook
When the error popped up, clicked debug
Right clicked on the "End Sub" line of the WorkBook_Open sub and clicked "Set Next statement"
Pressed F5 to allow the code to finish executing
Saved the workbook and it all works now!
I had another crash with the subsequent run-time error and repeated the steps above and it worked a charm again.

VBA macro crashing Excel 2010

I have an Excel 2010 spreadsheet that I use to maintain tests for an automated test application written with Selenium WebDriver. The spreadsheet has 6 ActiveX buttons that Upload (to a database), Import (from another sheet), Clear All Sheets, Export (to another sheet), Merge (two sheets), and Restore (a test suite from the database). My problem seem to stem from the macro that runs when the Import button is selected
The macro takes two sheets, source and destination, clears the destination sheet and copies the cells and data from the source workbook to the corresponding sheet in the destination workbook. From there, it can either be uploaded to the database or run from the sheet by the testing app
A couple weeks ago when selecting the Import button Excel crashed. I looked on the web and found a solution that worked. It involved disabling all macros, shutting down trust documents and trusted locations, recompiling, and reopening the workbook. This worked for a couple weeks until the same thing happened again this past weekend and the fix did not work anymore.
Here is the code I have:
numSheets = wrkBook.Sheets.Count
appName = wrkSheet.Cells(2, 3).Value
bkPath = Application.GetOpenFilename("Excel Macro-Enabled Workbook (*.xlsm),*.xlsm")
If bkPath <> "False" Then
Call Clear_All(wrkBook, wrkSheet)
'get the number of sheets in the source workbook
destCnt = wrkBook.Sheets.Count
Set importBook = Workbooks.Open(bkPath)
For a = 1 To destCnt
thsShtName = wrkBook.Worksheets(a).Name
'activate the source workbook
importBook.Activate
'get the numer of sheets in the source workbook
srcCnt = importBook.Sheets.Count
'loop through each sheet checking title
For b = 1 To srcCnt
'get the name of the 'a' sheet
**srcSheetName = importBook.Worksheets(b).Name**
'do more stuff with the source sheet
Next b
Next a
End If
The code is crashing on the following line
srcSheetName = importBook.Worksheets(b).Name
Here are a few things that I have noticed. Once the importBook variable is set, I cannot expand the variable in a watch window even if the code has not reached the offending line. However, the macro will successfully get the srcCount (number of sheet on the source sheet). Once the macro gets to the offending line it crashes consistently with a message stating simply that Excel has encountered an error and needs to close . No information, Excel closes, and sometimes restarts to a blank workbook
OK...I figured this out myself after heeding Siddarth Rout's suggestion about a corrupt spreadsheet. I took the steps that I described above
So here's what I did.
I copied one of the other spreadsheets and cleared it. As soon as I ran the Import macro, it passed through the line where it was failing before, so a corruption seems to have been the issue. I then stepped through the original code and rewrote the Import macro to simplify the code in it. It now seems to be working just fine
Thanks for the suggestions!!

Run-time error '-2147188160(80048240) DataType:=ppPasteEnhancedMetafile Error

Seems there is some bug. Can't resolve this problem, all code is running fine and I am able to see the AutoShape is getting copied from Excel file but it is not adding it to PowerPoint. Popping up an error Run-time error '-2147188160(80048240) View.Pastespecial : Invalid Request. The specified data type is unavailable
If Range("H" & i).Value = 1 And Range("B" & i).Value = "FRONT" Then
objPPT.Presentations(1).Slides(9).Select
objPPT.ActiveWindow.View.PasteSpecial DataType:=ppPasteEnhancedMetafile
Your code will be faster and possibly more reliable if you don't rely on selecting anything:
With objPPT.Slides(9).Shapes
Set objShape = .PasteSpecial(ppPasteEnhancedMetafile)(1)
With objShape
' set coordinates and such here
End With
End With
As to why you're getting the error message, try stopping the code after you've put something on the clipbard. Then switch to PowerPoint, use Paste Special to see what paste options are available. If EMF isn't one of them, that's your problem ... you're not putting anything in EMF format on the clipboard.
I had a similar issue, but I found a different solution; it may be specific to what I was doing though.
I setup a program where I would:
(manual) Copy an entire webpage that was a report on several performance metrics
(manual) Pasted it in to excel
Run the program to extract the values I want and then clear contents of the sheet I pasted them on.
Eventually after many tests, it would fail with this same automation error when I tried to access the sheet:
Sheets("PDX Paste").Activate
I was able to activate every other sheet except that particular one, even using the index value instead of the direct name reference. After googling to no success I found out that the copy and paste from the website was also pasting invisible controls. When I found this out I had 1,300+ shapes when I only expected 1 (the button I use to trigger the program). It was actually only apparent when a glitch - presumably due to so much memory being used to store these controls - displayed for a few seconds.
I ran the following code independently and then appended it to the end of my program when I do the cleanup of the data. The code goes through the sheet and deletes any shape that isn't the same type as my button. It would have to be adapted if the shapes you want to delete are the same type as the shapes you want to keep. It also becomes simpler if you don't have any shapes to keep.
Dim wsh As Worksheet
Set wsh = ActiveSheet
Dim i As Integer
For i = wsh.Shapes.Count To 1 Step -1
If wsh.Shapes(i).Type <> wsh.Shapes("UpdateDataButton").Type Then
wsh.Shapes(i).Delete
End If
Next i
I'm not sure this would solve this problem, but hopefully this can help others and prevent loss of time figuring out what may be causing this relatively vague error message.