Excel: VBA script error Run-time error '2147417848 (80010108)' - vba

Using the follow VBA codes to run two separate procedures which I am calling via separate buttons.
Depending on the order I run them, I get the Run-time error:
DeleteSheets1 = No error GetSheets - No error DeleteSheets1 + GetSheets - Error!
DeleteSheets1, (Close and reopen Excel), GetSheets - NoError
GetSheets, DeleteSheets1 - No Error
GetSheets, GetSheets, GetSheets - No Error
Sub DeleteSheets1()
Dim xWs As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In Application.ActiveWorkbook.Worksheets
If xWs.Name <> "Master" Then
xWs.Delete
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
-------------------------------------------------
Sub GetSheets()
Dim path As String, Filename As String, sheet, Awb As Workbook
path = "mypathhere"
Filename = Dir(path & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=path & Filename, ReadOnly:=True
Set Awb = ActiveWorkbook
For Each sheet In Awb.Worksheets
sheet.Copy After:=ThisWorkbook.Sheets(1)
Next sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
Given that closing and reopening Excel prevents the error, I wonder if it is either memory based, or my delete sub is not clearing what is needed?

Ok I have found a workable solution
Sub Reopen()
'Sets as active, saves and reopens workbook
Dim wb As Excel.Workbook
Set wb = ThisWorkbook
Dim pth As String
pth = wb.FullName
Application.DisplayAlerts = False
Application.OnTime Now + TimeValue("00:00:01"), Application.Workbooks.Open(pth)
wb.Close (True)
Application.DisplayAlerts = True
End Sub
Calling the above procedure immediately following DeleteSheets1; Excel saves and reopens the Workbook. This clears the cache, meaning GetSheets runs without error.

Related

Copy a specific worksheet from multiple workbooks without openeing the workbook

I have a code below which copies a specific worksheets form all active or open workbooks.
But how to copy the same Worksheet without opening the workbooks, like if we can provide the path in the code , it should be able to pick the given worksheet from all the workbooks form that path.
Below is the code that am currently using.
Sub CopySheets1()
Dim wkb As Workbook
Dim sWksName As String
sWksName = "SHEET NAME"
For Each wkb In Workbooks
If wkb.Name <> ThisWorkbook.Name Then
wkb.Worksheets(sWksName).Copy _
Before:=ThisWorkbook.Sheets(1)
End If
Next
Set wkb = Nothing
End Sub
Work with Workbooks.Open Method to open it in in the background, and hide any alerts with Application / ScreenUpdating / EnableEvents / DisplayAlerts
Application.ScreenUpdating Property (Excel) Turn screen updating off to speed up your macro code. You won't be able to see what the macro is doing, but it will run faster.
Example
Sub CopySheets1()
Dim wkb As Workbook
Dim sWksName As String
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
wkb Workbooks.Open("C:\temp\bookname.xls")
sWksName = "SHEET NAME"
For Each wkb In Workbooks
wkb.Worksheets(sWksName).Copy _
Before:=ThisWorkbook.Sheets(1)
Next
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
Set wkb = Nothing
End Sub
Assuming your folder name is C:\Temp\ then Loop until folder returns an empty
Example
Dim FileName As String
' Modify this folder path as needed
FolderPath = "C:\Temp\"
' Call Dir the first time to all Excel files in path.
FileName = Dir(FolderPath & "*.xl*")
' Loop until Dir returns an empty .
Do While FileName <> ""
' Open a workbook in the folder
Set wkb = Workbooks.Open(FolderPath & FileName)
'--->> Do your copy here
' Close the source workbook without saving changes.
wkb.Close savechanges:=False
' next file name.
FileName = Dir()
Loop
Use a Do...Loop structure when you want to repeat a set of statements an indefinite number of times, until a condition is satisfied. If you want to repeat the statements a set number of times, the For...Next Statement is usually a better choice.
I am assuming that you don't want to display the opened workbook to the user so the operation is not visible on screen.
If that's the case, you can use the following line before your code
Application.ScreenUpdating = False
'open the new/target excel workbook and put all the sheets in there
And following after:
Application.ScreenUpdating = True
It seems then that you have to manually open the workbooks. You can automate this process in VBA as follows;
Sub CopySheets1()
Dim wkb As Workbook
Dim dirPath As String ' Path to the directory with workbooks
dim wkbName as String
dirPath="C:\folder\"
sWksName = "SHEET NAME"
wkbName=Dir(dirPath & "*.xlsx")
For example:
dirPath = "C:\folder\"
So that the input to the Dir function be like "C:\folder*.xlsx"
Application.DisplayAlerts = False
do while wkbName <> ""
Set wkb=Application.Workbooks.Open(dirPath & wkbName)
wkb.Worksheets(sWksName).Copy _
Before:=ThisWorkbook.Sheets(1)
wk.Close False
wkbName = Dir
loop
Application.DisplayAlerts = True
End Sub

VBA Excel not responding when copy data to another workbook

I use this simple code to copy my sheet from workbook 1 into workbook 2 in the same folder.
Sub Button27_Click()
Application.ScreenUpdating = False
Dim FileName As String
Workbooks.Open FileName:=ActiveWorkbook.Path & "\sefaresh.xlsm"
Application.Wait (Now + TimeValue("0:00:01"))
ThisWorkbook.Sheets("Sheet3").Copy
After:=Workbooks("sefaresh.xlsm").Sheets(Sheets.Count)
Application.ScreenUpdating = True
End Sub
The copy&paste function process successfully but if i close the workbook 2 first, i get not responding for excel. Any suggestion?
Thanks
Try this (Untested). You shouldn't get an error now.
Things become easier if you work with objects :)
Sub Button27_Click()
Dim wbThis As Workbook, wbThat As Workbook
Dim ws As Worksheet
Dim fName As String
On Error GoTo Whoa
Set wbThis = ThisWorkbook
Set ws = wbThis.Sheets("Sheet3")
fName = wbThis.Path & "\sefaresh.xlsm"
Application.ScreenUpdating = False
Set wbThat = Workbooks.Open(fName)
DoEvents
ws.Copy After:=wbThat.Sheets(wbThat.Sheets.Count)
'~~> close and save the workbook
wbThat.Close (True)
DoEvents '<~~ Give time for it to save and close
LetsContinue:
Application.ScreenUpdating = True
MsgBox "Done"
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub

VBA Code Works in Excel 2010 But Not Excel 2013

I have code in VBA that copies worksheets with the same tab name from different workbooks into one workbook. The workbooks that the code pulls from is in one folder. The code is working fine in Excel 2010 however when I run it in Excel 2013, I get the following 1004 error message: "Sorry, we couldn't find ....xlsx. Is it possible it was moved, renamed or deleted." I'm not sure where to start troubleshooting. Has anyone run into this problem or have any ideas why it would be working fine in Excel 2010 and not Excel 2013? Thank you.
Sub CombineSheets()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim wSht As Variant
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = "PathName\Inputs"
ChDir sPath
sFname = "*"
sFname = Dir(sPath & "\" & sFname & ".xlsx*", vbNormal) <Code bombs here>
wSht = ("Risks")
Do Until sFname = ""
Set wBk = Workbooks.Open(sFname)
Windows(sFname).Activate
Sheets(wSht).Copy Before:=ThisWorkbook.Sheets(1)
wBk.Close False
sFname = Dir()
Loop
ActiveWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
Are you sure this code has previously worked?
If it did, then your application's default file path has probably changed. You can check this with Debug.Print Application.DefaultFilePath In any event, you'd be better off defining your full path name explicitly in your sPath variable.
If you want to pick up legacy Excel documents then the string in your Dir function could just be "*.xls*" (but that would also collect macro-enabled workbooks). I wonder if that was originally intended with the asterix in your code.
There's no need to activate the window, but you might want an error handling line to check whether the "Risks" sheet does exist in the workbook.
There's also some redundancy in your code, so the whole thing ought to work okay as given below:
Sub CombineSheets()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim wSht As Worksheet
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = "PathName\Inputs" 'make this a full path eg "C:\..."
sFname = Dir(sPath & "\" & "*.xls*", vbNormal)
Do Until sFname = ""
'skip if it's this workbook
If sFname <> ThisWorkbook.Name Then
Set wBk = Workbooks.Open(sPath & "\" & sFname)
'check a "Risks" sheet exists
Set wSht = Nothing
On Error Resume Next
Set wSht = wBk.Sheets("Risks")
On Error GoTo 0
If Not wSht Is Nothing Then
wSht.Copy Before:=ThisWorkbook.Sheets(1)
End If
wBk.Close False
End If
sFname = Dir()
Loop
ActiveWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

How to copy a single tab from a workbook into a master workbook using VBA on excel

I'm trying to pull one tab into a master workbook from a number of workbooks in a specified folder. so far this is what I have:
Sub GetSheets()
Path = "D:\APQP\APQP\Open Projects\"
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheets("5-Phase").Select
Sheets("5-Phase").Copy Before:=ThisWorkbook.Sheets(1)
Next
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
Right now when I run it, it populates the master workbook with 50 of the tabs from the first wookbook in the folder instead of coping the tab and moving on to the next workbook and coping the tab in that workbook. Any help would be great.
You have two major problems with your code. The For loop is unnecessary and you aren't working with the opened workbook. Something like this should work for you:
Sub GetSheets()
Dim wb As Workbook
Dim sPath As String
Dim sFileName As String
Set wb = ThisWorkbook
sPath = "D:\APQP\APQP\Open Projects\"
sFileName = Dir(sPath & "*.xlsx")
Application.ScreenUpdating = False
Application.EnableEvents = False
On Error Resume Next
Do While Len(sFileName) > 0
With Workbooks.Open(sPath & sFileName, ReadOnly:=True)
.Sheets("5-Phase").Copy Before:=wb.Sheets(1)
.Close False
End With
sFileName = Dir()
Loop
On Error GoTo 0
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub

Error importing sheets in VBA

I'm trying to write a VBA macro to import a sheet from another workbook. I get a "subscript out of range" error on the "copy" line. The file opens correctly, but I'm not sure what goes wrong after that.
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim lastdate As String, filename As String
lastdate = Format(sheet_1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Workbooks.Open (filename)
Workbooks(filename).Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
Workbooks(filename).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = False
End Sub
Edit: error changed to "subscript out of range", code changed so worksheets referenced by index.
Code v2:
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim lastdate As String, filename As String
lastdate = Format(sheet1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Dim wbk As Workbook
wbk = Workbooks.Open(filename)
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
wbk.Close
End Sub
You get the subscript out of range error because you don't have the workbook's Name right. The Name isn't the same thing as the full path (which is what you have been assuming); it's the same thing as the filename.
This will work:
Workbooks.Open "C:\Dir\file1234.xlsm"
Workbooks("file1234.xlsm").Sheets(1).Range("a1").Value = "yay"
Whereas this won't:
Workbooks.Open "C:\Dir\file1234.xlsm"
Workbooks("C:\Dir\file1234.xlsm").Sheets(1).Range("a1").Value = "yay"
But a much better way to reference a workbook is to set an explicit reference to it like this:
Dim wbk As Workbook
Set wbk = Workbooks.Open(filename)
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
With wbk you now have a handle on the workbook you want; you don't have to guess its name or anything.
The keyword 'Set' is required when referencing an object variable:
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
'Application.DisplayAlerts = False '<<this does not look like it is required - when is an alert displayed in the method?
Dim lastdate As String, filename As String
lastdate = Format(sheet1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"
Dim wbk As Workbook
Set wbk = Workbooks.Open(filename) '<<Set is required
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
wbk.Close
End Sub
Option Explicit
Sub Import_Worksheets()
Dim FolderPath As String
Dim Filename As String
Dim sheet As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = "H:G:\D S Class\Excel VBA (Macro)\RTO form\VBA\"
Filename = Dir(FolderPath & "RESTAURANT_USAGE_DATA.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each sheet In ActiveWorkbook.Sheets
sheet.Copy After:=ThisWorkbook.Sheets(1)
Next sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
enter code here