Create Copy Of Excel Worksheet using Word VBA - excel

With an already-opened workbook, I want to create a copy of a worksheet ("Template") and re-name it with the value I have in an array. When I debug the code the copy is created when I execute the line but I still get an error 424: object required.
I've tried On Error Resume Next but since I already used On Error GoTo in my sub it isn't read.
Dim oXL As Excel.Application 'Requires loading "Microsoft Excel 16.0 Object Library" from Tools -> References
Dim oWB As Excel.Workbook
Set oXL = New Excel.Application
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn) 'Opens Excel
oXL.Visible = True 'Shows Excel window while running code. Set to false after finished editing.
Dim ws As Worksheet
For i = LBound(seller_names) To UBound(seller_names)
'On Error Resume Next 'Doesn't work
Set ws = oXL.ActiveWorkbook.Sheets("Template").Copy(After:= _
oXL.ActiveWorkbook.Sheets(oXL.ActiveWorkbook.Sheets.Count))
ws.name = seller_names(i)
Next i

Sheets.Copy doesn't return a reference to the copied sheet, so you need to first copy the sheet, then get a reference to it:
With oXL.ActiveWorkbook
.Sheets("Template").Copy After:= .Sheets(.Sheets.Count)
Set ws = .Sheets(.Sheets.Count)) '<< get the copy
ws.name = seller_names(i)
End With
On Error Resume Next should always work - but is not always a good solution - unless you have "Break on all errors" enabled in your VBA Options.

Related

Resize a dynamic table in another workbook

I have two workbooks. One is macro enabled that scrapes data together and puts in nicely formatted into another plain workbook. This helps with security issues for users who can't run macros.
I have done a lot without issue, but here I'm stuck. I made a very simple example:
Sub Test()
Dim appExcel As Excel.Application
Dim wDatabase As Workbook
Dim ob As ListObject
Set appExcel = CreateObject("Excel.Application")
'DOESN'T WORK when run from another workbook
Set wDatabase = appExcel.Workbooks.Open("C:\Test\Book1.xlsx")
'WORKS when macro run in the book with the table (and above line commented out)
'Set wDatabase = ActiveWorkbook
Set ob = wDatabase.Sheets("Sheet1").ListObjects("Table1")
ob.Resize Range("$B$3:$D$13")
'Save changes
wDatabase.Save
wDatabase.Close
End Sub
Two workbooks: Book1.xlsx and Book2.xlsm
Book1.xlsx has a table ("Table1") on "Sheet1" in cells B3 to D14. I want to make it B3 to D13.
If I run the macro with that worksheet active (as shown with the commented out code). It works fine. When I try to do it from another workbook, it errors out. Sometimes it will say "Run-time error '1004': This action won't work on multiple selections." Other times Excel enters a corrupt mode and say
"Run-time error '-2147023170 (800706be0)'; Automation error. The
remote procedure call failed."
I cannot find a reason!
The range should resize.
*Edit: Changing this worked!
Set wDatabase = Workbooks.Open("C:\Test\Book1.xlsx") Thanks chris neilsen!
Resize a Table Using Another Instance of Excel (Error Handling)
Sub Test()
Dim IsSuccess As Boolean
On Error GoTo ClearError ' start error-handling routine...
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
Dim wb As Workbook: Set wb = xlApp.Workbooks.Open("C:\Test\Book1.xlsx")
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
Dim lo As ListObject: Set lo = ws.ListObjects("Table1")
' If you want to see how it works when an error occurs,
' uncomment the Err.Raise line.
' Create a breakpoint and in the Task Manager locate the new instance
' under Background Processes. If you don't use 'Quit', it will remain
' open after the procedure exits.
'Err.Raise 13
' With 'F8', step through the rest of the code to see its flow.
' In the Task Manager see how the instance is gone.
lo.Resize ws.Range("B3:D13") ' the header row needs to be 3
IsSuccess = True
ProcExit:
On Error Resume Next ' prevent endless loop if error in the following lines
If Not wb Is Nothing Then wb.Close IIf(IsSuccess, True, False)
If Not xlApp Is Nothing Then xlApp.Quit
On Error GoTo 0
Exit Sub
ClearError: ' ... continue error-handling routine
Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description
Resume ProcExit ' redirect to exit routine
End Sub

How to open an Excel workbook from Access

I currently have a string in Microsoft Access that is delegating functions to an external Application.
I have gotten so far as to copying a set of data from the external application.
I want to paste this into an excel workbook that is not open but exists. C:\Users\abcdef\Desktop KDNR.xlsx
how can I integrate this function into my sub procedure?
Thank you in advance
I attempted simply writing
Dim x as Workbook
set x = Workbooks.Open (" workbook name ")
Howoever, i got the compile error "user defined type not defined"
when i just write
Workbooks.Open (" workbook name ")
i get the compile error
"variable not defined"
Use Excel From Access
This is a basic example of how to work with Excel from Access.
It opens a new instance of Excel (whether Excel is open or not), opens the workbook, writes the string Test to cell A1 of worksheet Sheet1, saves and closes the workbook, and finally quits the Excel instance.
' If you haven't already, create a reference to
' "Tools->References->Microsoft Excel 16.0 Object Library"!
Sub Test()
Dim DestinationFilePath As String
DestinationFilePath = Environ("USERPROFILE") & "\DeskTop\KDNR.xlsx"
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
xlApp.Visible = True ' out-comment when done developing; default is 'False'
Dim wb As Workbook: Set wb = xlApp.Workbooks.Open(DestinationFilePath)
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
ws.Range("A1").Value = "Test"
wb.Close SaveChanges:=True
xlApp.Quit
End Sub

Excel Vba Copy Method of Worksheet fails - Copy from xlApp to ThisWorkbook

I posted a question recently on interacting with another WB in a separate instance of Excel.
How to add Open Workbook to "Application.Workbooks" collection and/or interact with Workbook
But I had hardcoded the copy/paste range for testing, and now I'm having trouble with coping the entire worksheet to the "main wb". Eg: xlApp.Worksheets(1).Copy After:=Application.ActiveWorkbook.Sheets(1)
I get the error Copy Method of Worksheet Failed and ideas how to adjust this to work?
Public Sub Copy_External_WB()
Dim xlApp As Excel.Application, xlBook As Worksheet, i As Long
For i = 1 To 10
On Error Resume Next
Set xlApp = GetObject("Book" & i).Application
If Err.Number = -2147221020 Then
Err.Clear: On Error GoTo 0
Else
On Error GoTo 0
Exit For
End If
Next i
If Not xlApp Is Nothing Then
Set xlBook = xlApp.Worksheets(1)
Debug.Print xlApp.hWnd, Application.hWnd
Else
MsgBox "No Excel session with Book(1 - 10) open could be found..."
xlApp.Quit: Exit Sub
End If
'Dim CopyFrom As Range
'Set CopyFrom = xlBook.Range("A1:AQ56")
'Dim DS As Worksheet
'Set DS = ThisWorkbook.Worksheets("Merged")
'DS.Range("A1:AQ56").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value
xlApp.Worksheets(1).Copy After:=Application.ActiveWorkbook.Sheets(1)
xlApp.DisplayAlerts = False
xlApp.Quit
xlApp.DisplayAlerts = True
Set xlApp = Nothing
End Sub
You cannot copy a whole sheet object between different Excel instances.
Options:
Use VBA to save the other workbook to file, then open it in the instance where your code is running, and copy the sheet to your workbook
Copy (eg) the UsedRange from the other instance's worksheet, then paste in your primary instance workbook

Access/Excel VBA Failing

I have an Access database that runs a macro that opens some Excel files and formats the sheets to prepare them for later use. This code has been running fine until my company applied the latest Office Updates, and now I am getting a compile error "Method or data member not found" and its happening on the line...
wDate = Mid(XlSheet.Range("B4").Value, 13, Len(XlSheet.Range("B4").Value))
singling out the "Range". I cannot figure out why this started happening. Thanks for any assistance. Full code below...
Function ExcelProcess()
'Variables to refer to Excel and Objects
Dim MySheetPath As String
Dim Xl As Excel.Application
Dim XlBook As Excel.Workbook
Dim XlSheet As Excel.Worksheet
Dim MyFile As Variant
Dim MySheet As Variant
Dim wBook As Variant
Dim wSheet As Variant
Dim wDate As Variant
Dim rng As Range
Dim cel As Range
MyFile = Array("w1.xlsx", "w2.xlsx", "w3.xlsx")
MySheet = Array("T2_IND", "APPR_IND", "SLG_APPR_IND", "SLG_IND", "C2A_IND", "C3_IND", "C4_IND", "T3_IND", "T4_IND", "C2B_IND")
For Each wBook In MyFile
' Tell it location of actual Excel file
MySheetPath = "\\fs1\Training\CSC_Training_Ops\Training Only\Buzzard\Pulled Data\" & wBook
'Open Excel and the workbook
Set XlBook = GetObject(MySheetPath)
'Make sure excel is visible on the screen
XlBook.Windows(1).Visible = True
For Each wSheet In MySheet
'Define the sheet in the Workbook as XlSheet
Set XlSheet = XlBook.Worksheets(wSheet)
wDate = Mid(XlSheet.Range("B4").Value, 13, Len(XlSheet.Range("B4").Value))
XlSheet.Range("A15").FormulaR1C1 = "WE_Date"
If XlSheet.Range("A16").Value <> "No data found" Then
Set rng = XlSheet.Range(XlSheet.Range("A16"), XlSheet.Range("A16").End(xlDown).Offset(-1))
For Each cel In rng.Cells
With cel
.FormulaR1C1 = wDate
.NumberFormat = "m/d/yyyy"
End With
Next cel
End If
XlSheet.Rows("1:14").Delete Shift:=xlUp
XlSheet.Range("A1").End(xlDown).EntireRow.Delete Shift:=xlUp
Next
XlBook.Close SaveChanges:=True
Next
'Clean up and end with worksheet visible on the screen
Set Xl = Nothing
Set XlBook = Nothing
Set XlSheet = Nothing
End Function
There isn't any apparent problems with the code itself.
Since this broke with when you updated the office, I would venture a guess that it is an issue with the reference.
Go to Tools->References->
Remove all references to Excel Object Library
Save & Close the Macro Worksheet (Shouldn't be necessary, but only takes a sec)
Re-Open
Add in reference to only the latest version of Microsoft Excel 1X.0 Object Library
If this does not solve the issue, you may have to run a repair on office
Control Panel -> Add Remove Programs
Locate Microsoft Excel (Or office suite)
Run Repair
Finally, it was suggested to try late binding. Remove the references to the Microsoft Excel Object Library and update your declarations to:
Dim Xl As Object
Dim XlBook As Object
Dim XlSheet As Object
Set Xl = CreateObject("Excel.Application")
Hope this helps!
Is it possible you got upgraded from Office 14.0 to 15.0 or 16.0? Hit Alt+F11 > Tools References and look for errors in the window that opens. Search for the correct reference and click it. As others have suggested, consider rewriting the code using some late binding methodologies.

Easy VBA Macro to list all worksheets generates error: Type Mismatch

I'm making a ExcelComparer but I bump into a probably obvious error, I clearly missed something.
I run a vba macro in Excel 2007
The exact error I get is "Run-time Error 13: Type Mismatch"
This happens when the loop tries to fetch the second worksheet.name .
So, the first sheetname is returned fine
Below you find the macro
Thanks in advance,
L
Sub compare()
Dim strWorkbook1, strWorkbook2 As String
Dim Workbook1, Workbook2 As Workbook
strWorkbook1 = Worksheets("Sheet1").Range("C5") & Worksheets("Sheet1").Range("D5")
strWorkbook2 = Worksheets("Sheet1").Range("C6") & Worksheets("Sheet1").Range("D6")
Set xlapp = CreateObject("Excel.application")
Set Workbook1 = xlapp.Workbooks.Open(strWorkbook1)
xlapp.Visible = False
Dim ws As Worksheet
For Each ws In Workbook1.Sheets
'ws.Select
If Not ws.Visible = xlSheetVeryHidden Then
MsgBox (ws.Name)
End If
Next ws
xlapp.Close
End Sub
Use this for your For loop:
For Each ws In Workbook1.Worksheets
From MSDN the difference between the Sheets and Worksheets properties are:
This property does not return macro sheets, charts, or dialog sheets.
Use the Sheets property to return those sheets as well as worksheets.
You can also use the specialized properties Excel4MacroSheets and
Excel4IntlMacroSheets to return macro sheets and the Charts property
to return charts.
[Edited my original response as I had tested with different variables rendering my comment incorrect]
In addition the back end of your code will fail as you can't set the Excel Application to close with this line xlapp.Close
You should
close the automated workbook (Workbook1.Close False)
quit the automated application (xlapp.Quit)
Ensure the automated application is destroyed (Set xlapp = Nothing)a
The working part of your code should look like this
Dim ws As Worksheet
For Each ws In Workbook1.WorkSheets
If Not ws.Visible = xlSheetVeryHidden Then MsgBox (ws.Name)
Next ws
Workbook1.Close False
xlapp.Quit
Set xlapp = Nothing
End Sub

Resources