Delete Worksheet from Access 2010 VBA - excel

I have a form that exports and edits excel files for users. I have an issue when trying to have my code delete an existing worksheet from my Access 2010 VBA code.
My Code:
Private Sub Command0_Click()
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Dim sht As Excel.Worksheet
Set xl = CreateObject("Excel.Application")
Set wb = xl.Workbooks.Open("C:\Users\Me\Desktop\Document.xlsx")
For Each sht In wb.Worksheets
If sht.Name = "DeleteSheet" Then
wb.Worksheets("DeleteSheet").Delete
End If
Next sht
wb.Save
wb.Close
xl.Quit
End Sub
When I run the code, there is no error. However, the sheet does not get deleted. I know that sht.Name does read the sheet name "DeleteSheet", allowing the if statement to run. So, I believe it comes down to either the saving method or this line: wb.Worksheets("DeleteSheet").Delete. TIA!

Can you delete the worksheet directly, i.e.
Instead of
wb.Worksheets("DeleteSheet").Delete
Use
sht.Delete

Can you try something like this, Ryan?
Dim xl As Object
Dim wb As Excel.Workbook
Dim sht As Excel.Worksheet
Set xl = CreateObject("Excel.Application")
xl.Application.DisplayAlerts=False
Set wb = xl.Workbooks.Open("C:\Users\Me\Desktop\Document.xlsx")
For Each sht In wb.Worksheets
If sht.Name = "DeleteSheet" Then
wb.Worksheets("DeleteSheet").Select
xl.ActiveSheet.Delete
End If
Next sht
wb.Save
wb.Close
xl.Quit

Related

Copy Word Paragraph to Excel Cells

I am trying to copy Word paragraphs to Excel cells, but I am hung up on
Runtime error 9: Subscript out of range.
I have searched. Everything I read says it cannot find the file, but the file is in the same folder, and the name is not mis-spelled, and the extension is correct. So, I am stumped. The original code comes from here: How to copy a formatted paragraph from Word 2013 to Excel?.
Private Sub Load_Schedule()
Dim ParaCount As Integer
Dim wDoc As Word.Document
Dim wb As Workbook
Dim ws As Worksheet
Set wDoc = ActiveDocument
Set wb = Workbooks("new.xlsm")
Set ws = wb.Sheets("Sheet1")
ws.Activate
ws.Columns(1).AutoFit
For ParaCount = 1 To wDoc.Paragraphs.Count
wDoc.Paragraphs(ParaCount).Range.FormattedText.Copy
Sheets(ws).Cells(ParaCount, 1).PasteSpecial
Paste:=xlPasteFormats
Next ParaCount
End Sub
The error comes on this line: Set wb = Workbooks("new.xlsm")
As you work with both applications, you should use full declarations like Word.Document and Excel.Workbook (if you already referenced the appropriate libraries).
An already opened Excel file can be referenced without path.
The Paste:= ... parameter belongs to the previous code line, so you have to add a blank + undersore at the end of the previous line or put them together into one line.
Please reference your worksheet's cell by ws.Cells ... and not by Sheets(ws), as your "ws" already is a worksheet object and not a string.
The further answer depends, if you run your code from Word-VBA or from Excel-VBA.
Word VBA
If you want to reference an Excel file from Word-VBA, you need the Excel.Application object additionally.
If Excel is already started, you can use the existing application object - otherwise you create one and make it visible.
Same with your Excel file: If it's already open, you use it - if not, you open it.
Private Sub LoadSchedule()
Dim ParaCount As Integer
Dim wDoc As Word.Document
Dim objExcel As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
On Error Resume Next
Set objExcel = GetObject(, "Excel.Application")
On Error GoTo 0
If objExcel Is Nothing Then
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
End If
On Error Resume Next
Set wb = objExcel.Workbooks("new.xlsm")
On Error GoTo 0
If wb Is Nothing Then
Set wb = objExcel.Workbooks.Open(objExcel.DefaultFilePath & "\new.xlsm")
' or ThisDocument.Path or whatever path
End If
Set wDoc = ActiveDocument
Set ws = wb.Sheets("Sheet1")
For ParaCount = 1 To wDoc.Paragraphs.Count
wDoc.Paragraphs(ParaCount).Range.FormattedText.Copy
ws.Cells(ParaCount, 1).PasteSpecial Paste:=xlPasteFormats
Next ParaCount
ws.Columns(1).AutoFit
'ws.Activate
End Sub
Excel VBA
In Excel you can try to reference an already opened Word file directly as ActiveDocument without getting the Word.Application additionally.
Private Sub LoadSchedule()
Dim ParaCount As Integer
Dim wDoc As Word.Document
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
On Error Resume Next
Set wb = Workbooks("new.xlsm")
On Error GoTo 0
If wb Is Nothing Then
Set wb = Workbooks.Open(Application.DefaultFilePath & "\new.xlsm")
End If
Set wDoc = ActiveDocument
Set ws = wb.Sheets("Sheet1")
For ParaCount = 1 To wDoc.Paragraphs.Count
wDoc.Paragraphs(ParaCount).Range.FormattedText.Copy
ws.Cells(ParaCount, 1).PasteSpecial Paste:=xlPasteFormats
Next ParaCount
ws.Columns(1).AutoFit
'ws.Activate
End Sub
You need to specify the full path to the excel file - you say it's the same as the word document so this will work:
Sub GetXLFileInWord()
Dim xl As Excel.Application
Set xl = New Excel.Application
Dim wb As Excel.Workbook
Set wb = xl.Documents.Open(ThisDocument.Path & "\new.xlsm")

VBA code to print every worksheet in workbook as legal size

I tried the following code but it doesn't seem to work - can someone help me debug?
Sub printt()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open("link to file")
For Each ws In wb
ws.PageSetup.PaperSize = xlPaperLegal
Next
For Each ws In wb
ws.PrintOut
Next
End Sub
Sub printt()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks.Open("link to file")
For Each ws In wb.worksheets
ws.PageSetup.PaperSize = xlPaperLegal
ws.PrintOut
Next ws
End Sub

VBA - How to reference two separate open workbooks without naming them?

I have looked around for awhile and cant seem to locate what I need.
Refer to Workbooks
If you know there are only two workbooks open, you can use the Index property.
Sub ReferToWorkbooks()
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = Workbooks(1)
Set wb2 = Workbooks(2)
Debug.Print wb1.Name
Debug.Print wb2.Name
End Sub
It is better to loop through all open workbooks and then create references to the ones you need.
Sub ReferToWorkbooks2()
Dim wb As Workbook
For Each wb In Workbooks
Debug.Print wb.Name
Next
End Sub
In case you have a worksheet in your code you use the Parent property:
Sub ReferToWorkbooks3()
Dim ws As Worksheet
Dim wb As Workbook
Set ws = Worksheets("Sheet1")
Debug.Print ws.Parent.Name
' or
Set wb = ws.Parent
Debug.Print wb.Name
End Sub
In case you have a range in your code you use the Parent property twice:
Sub ReferToWorkbooks4()
Dim rng As Range
Dim wb As Workbook
Set rng = Range("A1")
Debug.Print rng.Parent.Parent.Name
' or
Set wb = rng.Parent.Parent
Debug.Print wb.Name
End Sub
You should better explain the scenario where you might need this.

Copy/Paste cells & value

I want to copy/paste all worksheet inlcuding the values/formula in the cells to another new workbook.
This code just copy the first ws, but not all other. How can I make sure, that all ws are gettin copied and pasted without writing all the names from the ws in the vba-code?
Sub CopyPaste()
Dim ws As Worksheet, wb As Workbook
Set ws = ActiveSheet
Set wb = Workbooks.Add(xlWBATWorksheet)
ws.Range("A1:G10").Copy
wb.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
End Sub
So i assume you will be saving the second workbook for it to be named? therefore just add your path below where you want to save it, also it now retains the sheet names.
I'm not sure why you are getting a debugger error its working fine for me, try this code and see if you still get it?
Sub newworkbook()
Dim WBN As workbook, WBC As workbook, WB As workbook
Dim WS As String
Dim SHT As Worksheet
Set WBN = Workbooks.Add
For Each WB In Application.Workbooks
If WB.Name <> WBN.Name Then
For Each SHT In WB.Worksheets
SHT.Copy After:=WBN.Sheets(WBN.Worksheets.Count)
WBN.Sheets(WBN.Worksheets.Count).Name = (SHT.Name) & " "
Next SHT
End If
Next WB
Application.DisplayAlerts = False
WBN.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete
WBN.Application.DisplayAlerts = True
ActiveWorkbook.SaveAs "C:\YOURPATH\timetable_v2.xls" 'change path to whatever
End Sub
You can try as follow:
Sub CopyPaste()
Dim aSheet As Worksheet
Dim workbook As workbook
Dim index As Integer
Set workbook = Workbooks.Add(xlWBATWorksheet)
For Each aSheet In Worksheets
aSheet.Range("A1:G10").Copy
workbook.Sheets(index).Range("A1").PasteSpecial Paste:=xlPasteFormulasAndNumberFormats
index = index + 1
Application.CutCopyMode = False
Next aSheet
End Sub
Just had a quick look for you, this seems to do the job:
credit: get digital help
Dim WBN As Workbook, WBC As Workbook, WB As Workbook
Dim WS As String
Dim SHT As Worksheet
Set WBN = Workbooks.Add
For Each WB In Application.Workbooks
If WB.Name <> WBN.Name Then
For Each SHT In WB.Worksheets
SHT.Copy After:=WBN.Sheets(WBN.Worksheets.Count)
WBN.Sheets(WBN.Worksheets.Count).Name = Left(WB.Name, 30 - Len(SHT.Name)) & "-" & SHT.Name
Next SHT
End If
Next WB
Application.DisplayAlerts = False
WBN.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete
WBN.Application.DisplayAlerts = True
I just deleted WBN.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete
And it works fine
The new workbook is saved as an .xlsx file, but of course I Need it as an .xlsm file....when I just added it into the path, it doesnt work
ActiveWorkbook.SaveAs "U:\Excel\timetable_v2.xlsm"

Why does Worksheet.Copy not return a reference to the new workbook created

I have some code where wb is an existing multi-worksheet workbook. If I copy one of the sheets "Overview" a new workbook is created - so why does the following error saying "object required"?:
Dim wbCopy As Excel.Workbook
Set wbCopy = wb.Sheets("Overview").Copy
The Worksheet.Copy method doesn't return a reference to the new Workbook. You might use a Worksheet reference instead:
Dim wsCopy As Excel.Worksheet 'changed from wb to wsCopy
As you know, if you don't supply either the After or Before argument it copies to a new Workbook. Copying within the same workbook would use this code:
Set wsCopy = wb.Worksheets("Overview")
wsCopy.Copy After:= wb.Worksheets(1) 'or Before:=
If you want to copy the sheet to a new workbook, and retain a reference to it, then this needs to be done in stages:
Dim wbNew As Excel.Workbook
Dim wsCopied As Excel.Worksheet
Set wbNew = Workbooks.Add
wsCopy.Copy before:=wbNew.Worksheets(1)
Set wsCopied = wbNew.Worksheets(1)
If you only need to keep a reference to the new workbook then just omit the last line (and the variable declaration for wsCopied).
This is one of the few occasions you have to use one of the Active* objects
wb.Sheets("Overview").Copy
Set wbCopy = ActiveWorkbook
The worksheets copy method appears to return a boolean value rather than a workbook object. To set a reference to the workbook you can use the following.
Sub wbcopy()
Dim wbcopy As Excel.Workbook
Dim wbIndex As Excel.Workbook
Dim sArray() As String
Dim iIndex As Integer
Dim bfound As Boolean
Dim wb As Workbook
Set wb = ThisWorkbook
ReDim sArray(Workbooks.Count)
'Find the names of all the current workbooks
For Each wbIndex In Workbooks
sArray(iIndex) = wbIndex.FullName
Next wbIndex
'Copy the sheet to a new workbook
wb.Sheets("Overview").Copy
'Find the sheet with the new name
For Each wbIndex In Workbooks
bfound = False
For iIndex = LBound(sArray) To UBound(sArray)
If wbIndex.FullName = sArray(iIndex) Then
bfound = True
Exit For
End If
Next iIndex
If Not bfound Then
Set wbcopy = wbIndex
Exit For
End If
Next wbIndex
End Sub
I ran into the same thing today. To me the active* objects is too vague so I looked for a way to reliably determine the sheet object.
Just if anyone's looking for this, here's for the files:
dim sws, tws as worksheet
set sws = thisworkbook.sheets("source")
sws.copy before:=sws
set tws = sws.previous
That does the job
rn43x

Resources