Hi,
After years of coding in other languages I have been asked to "automate" some Excel workbook actions, so this is my one of my first attempts using VBA.
One of them is copying the used cells in a couple of worksheets to a new workbook.
This VBA code works fine if run by clicking a button on the workbook, but if I press the F5 key from within the VBA environment it produces a runtime 91 error.
It looks like the problem is in the "For Each ws..." construct, so I thought it might be something to do with not having a "SET ws" line. However adding various forms of such a construct, e.g. Set ws = Activesheet (see code example above) does not stop the problem.
I know the code works ok outside of the development environment, but am trying to understand why this error occurs within it.
Thanks for your help
After years of coding in other languages I have been asked to "automate" some Excel workbook actions, so this is my one of my first attempts using VBA.
One of them is copying the used cells in a couple of worksheets to a new workbook.
This VBA code works fine if run by clicking a button on the workbook, but if I press the F5 key from within the VBA environment it produces a runtime 91 error.
Code:
Function CreateCopy() As String
Dim ws As Worksheet
Dim iDataEnd As Integer
Dim iSumEnd As Integer
Dim sFilename As String
Dim sDir As String
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'Change text in below cell to where month's worksheet being stored after saving
sDir = Worksheets("Names").Range("I3").Value
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Application.ScreenUpdating = False
iDataEnd = LastDataRow("A", 2, "Data")
iSumEnd = LastDataRow("A", 2, "Summary")
'Construct filename to save new workbook as
sFilename = NewFileName()
Worksheets(Array("Data", "Summary")).Copy
ActiveWorkbook.Worksheets("Data").Rows(iDataEnd + 1 & ":" & Worksheets("Data").Rows.Count).Delete
ActiveWorkbook.Worksheets("Summary").Rows(iSumEnd + 1 & ":" & Worksheets("Data").Rows.Count).Delete
Set ws = ActiveWorkbook.Worksheet(1) '<---- Thought this might be problem line
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
ws.Cells.PasteSpecial xlPasteValues
Next
Application.CutCopyMode = False
ActiveWorkbook.SaveAs Filename:=sDir & sFilename
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.ScreenUpdating = True
CreateCopy = sFilename
End Function
It looks like the problem is in the "For Each ws..." construct, so I thought it might be something to do with not having a "SET ws" line. However adding various forms of such a construct, e.g. Set ws = Activesheet (see code example above) does not stop the problem.
I know the code works ok outside of the development environment, but am trying to understand why this error occurs within it.
Thanks for your help