VBA Excel not responding when copy data to another workbook - vba

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

Related

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

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.

How do I execute a sub that doesn't display as a macro?

I found an excellent piece of code on this site that I'd like to add to my workbook:
Trim all cells within a workbook(VBA)
The code there is:
Sub DoTrim(Wb As Workbook)
Dim aCell As Range
Dim wsh As Worksheet
'~~> If you are using it in an Add-In, it is advisable
'~~> to keep the user posted :)
Application.StatusBar = "Processing Worksheets... Please do not disturb..."
DoEvents
Application.ScreenUpdating = False
For Each wsh In Wb.Worksheets
With wsh
Application.StatusBar = "Processing Worksheet " & _
.Name & ". Please do not disturb..."
DoEvents
For Each aCell In .UsedRange
If Not aCell.Value = "" And aCell.HasFormula = False Then
With aCell
.Value = Replace(.Value, Chr(160), "")
.Value = Application.WorksheetFunction.Clean(.Value)
.Value = Trim(.Value)
End With
End If
Next aCell
End With
Next wsh
Application.ScreenUpdating = True
Application.StatusBar = "Done"
End Sub
I've tried copying and pasting this into an Excel module, but can't figure out how to execute it. I'm really new at all this, so I apologize in advance if this is a stupid question. I've searched on why the Sub won't show up as a macro, and the best possible answer I've found is that it is because it contains variables?
I realize the original poster was trying to modify an Add-In; I'm just hoping there's a way to invoke this on a workbook.
Thanks!
The subroutine is expecting a Workbook as a parameter Sub DoTrim(Wb As Workbook), so you won't be able to run it from the macros window
If the Excel Module is in the same Workbook you want to trim, then you can remove the parameter and use the ThisWorkbook object instead to loop through the Worksheets in the Workbook, as below:
Sub DoTrim()
Dim aCell As Range
Dim wsh As Worksheet
'~~> If you are using it in an Add-In, it is advisable
'~~> to keep the user posted :)
Application.StatusBar = "Processing Worksheets... Please do not disturb..."
DoEvents
Application.ScreenUpdating = False
For Each wsh In ThisWorkbook.Worksheets
With wsh
Application.StatusBar = "Processing Worksheet " & _
.Name & ". Please do not disturb..."
DoEvents
For Each aCell In .UsedRange
If Not aCell.Value = "" And aCell.HasFormula = False Then
With aCell
.Value = Replace(.Value, Chr(160), "")
.Value = Application.WorksheetFunction.Clean(.Value)
.Value = Trim(.Value)
End With
End If
Next aCell
End With
Next wsh
Application.ScreenUpdating = True
Application.StatusBar = "Done"
End Sub

On workbook open, Excel Macro to refresh all data connections sheets and pivot tables and then export the pivot to csv

I have an Excel File which has CSV Data sources and Pivot tables, I want to refresh all the data sources and pivot tables automatically and export one pivot table as CSV on opening the excel file.
I tried the below code, but this code export the CSV file before the data getting refreshed.
please help with a solution. Thanks in advance.
Private Sub Workbook_Open()
ThisWorkbook.RefreshAll
Run "Macro1"
End Sub
Sub Macro1()
Dim ws As Worksheet, newWb As Workbook
Dim SaveToDirectory As String
SaveToDirectory = "C:\Macro\"
Application.ScreenUpdating = False
For Each ws In Sheets(Array("locationwise"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs SaveToDirectory & ws.Name, xlCSV
.Close (False)
End With
Next ws
Application.ScreenUpdating = True
Application.DisplayAlerts = False
End Sub
A simple DoEvents should do the trick! ;)
Try this :
Private Sub Workbook_Open()
ThisWorkbook.RefreshAll
DoEvents
Run "Macro1"
End Sub
And if it's not, just add this line after the DoEvents :
Application.Wait(Now + TimeValue("0:00:05"))
This will put on hold the execution of the code, here for 5 seconds!
If you want to launch the save parts once a specific range has been modified, place your that code into the sheet module :
Private Sub Worksheet_Change(ByVal Target As Range)
If Application.Intersect(Target, Me.Range(Rg_To_Check)) Is Nothing Then
'Not in range
Else
'In range to check
Run "Macro1"
End If
End Sub
And get rid of the Run "Macro1" in the Workbook_Open() event.
Also, be careful, because your last line is Application.DisplayAlerts = False you won't have alerts afterwards, you should use it like this instead :
Sub Macro1()
Dim ws As Worksheet, newWb As Workbook
Dim SaveToDirectory As String
SaveToDirectory = "C:\Macro\"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
For Each ws In Sheets(Array("locationwise"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs SaveToDirectory & ws.Name, xlCSV
.Close (False)
End With
Next ws
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Excel VBA Creating/overwriting a new workbook and using the cancel button

I have a macro written that take a range from one workbook and copies into into a new workbook, which then saves the newly created workbook (and gives it a name) into the same folder path. When this workbook already exists, (overwriting the workbook), the default windows dialogue box pops up asking if you would like to overwrite, with a yes no cancel selection of buttons. When the cancel button is pressed, a new workbook is created. How do I edit this code so that when cancel is pressed, no new workbook is created? I have pasted the macro below:
Sub ExportNewBook()
Application.ScreenUpdating = False
Dim ThisWB As Workbook
Set ThisWB = ActiveWorkbook
Set NewBook = Workbooks.Add
On Error Resume Next
ThisWorkbook.Worksheets("Summary").Range("A1:I100").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteFormats)
NewBook.Worksheets("Sheet1").Range("A:J").Columns.AutoFit
NewBook.SaveAs Filename:=ThisWB.Path & "\" & NewBook.Worksheets("Sheet1").Range("A4").Value & "_Summary"
NewBook.ActiveSheet.Range("A1").Select
Application.ScreenUpdating = True
End Sub
EDIT: WORKING CODE SHOWN BELOW
Sub ExportNewBook()
Application.ScreenUpdating = False
Dim ThisWB As Workbook
Dim fname As String
Set ThisWB = ActiveWorkbook
Set Newbook = Workbooks.Add
ThisWorkbook.Worksheets("Summary").Range("A1:I100").Copy
Newbook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
Newbook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteFormats)
Newbook.Worksheets("Sheet1").Range("A:J").Columns.AutoFit
fname = ThisWB.Path & "\" & ThisWB.Worksheets("Summary").Range("A4").Value & "_Summary.xls"
If Dir(fname) <> "" Then
If MsgBox("Summary output already exists, are you sure you want to overwrite?", vbOKCancel) = vbCancel Then Newbook.Close False: Application.CutCopyMode = False: Exit Sub
End If
Application.DisplayAlerts = False
Newbook.SaveAs Filename:=fname
Application.DisplayAlerts = True
ThisWB.Activate
ActiveWorkbook.Worksheets("Summary").Range("A1").Select
Newbook.Activate
ActiveWorkbook.ActiveSheet.Range("A1").Select
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Thank you!
On error resume next is seldom a good idea. If the user selects no or cancel, an error is triggered. Better to handle that error to delete the unwanted workbook (although another idea is to test if a workbook with the target name exists before creating it and, if it does, use msgbox to ask the user if they want to overwrite the file and, if so, only then create the workbook, disable alerts, and only then do saveas).
A problem seems to be that you need to have a filename to kill a workbook. In your situation the workbook doesn't yet have a filename. One solution is to create a safe filename whose sole purpose in life is to kill an unwanted workbook, do saveas again with this name, then kill it. Something like this:
Sub Test()
On Error GoTo err_handler
Dim wb As Workbook
Dim fname As String
Dim tempname As String
fname = "C:\Programs\testbook.xlsx"
Set wb = Workbooks.Add
wb.Sheets(1).Range("A1").Value = Now 'for testing purposes
wb.SaveAs fname
Exit Sub
err_handler:
tempname = "C:\Programs\name_i_will_never_use.xlsx"
wb.SaveAs tempname
wb.Close
Kill tempname
End Sub
Here is a possible approach:
Sub ExportNewBook()
Application.ScreenUpdating = False
Dim ThisWB As Workbook, Newbook As Workbook
Dim fname As String
Set ThisWB = ActiveWorkbook
fname = ThisWB.Path & "\" & ThisWB.Sheets("Sheet1").Range("A4").Value & "_Summary"
If Dir(fname) <> "" Then
If MsgBox("Are you sure you want to overwrite?", vbOKCancel) = vbCancel Then Exit Sub
End If
Set Newbook = Workbooks.Add
ThisWB.Worksheets("Summary").Range("A1:I100").Copy
Newbook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
Newbook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteFormats)
Newbook.Worksheets("Sheet1").Range("A:J").Columns.AutoFit
'This code should be faster since it bypasses the copy-paste buffer
'With Newbook.Sheets(1)
' ThisWB.Sheets("Summary").Range("A1:I100").Copy .Range("A1")
' .Range("A1:I100").Value = .Range("A1:I100").Value
' .Columns.AutoFit
'End With
Application.DisplayAlerts = False
Newbook.SaveAs Filename:=fname
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
this is the full code with
check if file already exist
if exist close the newbook and ask you if the existed file will be opened
close the newbook
in case of error save the newbook with (error) suffix before the extension file
Sub ExportNewBook()
Application.ScreenUpdating = False
Dim ThisWB As Workbook
Dim NewName As String
Set ThisWB = ActiveWorkbook
Set NewBook = Workbooks.Add
On Error GoTo err_handler
ThisWB.Worksheets("Summary").Range("A1:I100").Copy
NewBook.Worksheets("Foglio1").Range("A1").PasteSpecial (xlPasteValues)
NewBook.Worksheets("Foglio1").Range("A1").PasteSpecial (xlPasteFormats)
NewBook.Worksheets("Foglio1").Range("A:J").Columns.AutoFit
NewName = ThisWB.Path & "\" & NewBook.Worksheets("Foglio1").Range("A4").Value & "_Summary.xls"
If Dir(NewName) "" Then
If MsgBox("A file named '" & NewName & " already exists." & vbCr & vbCr & _
MeaName & " will now open??", vbYesNo) = vbYes Then
Workbooks.Open NewName
End If
NewBook.Close False
Exit Sub
End If
NewBook.SaveAs Filename:=NewName
NewBook.ActiveSheet.Range("A1").Select
NewBook.Close
Application.ScreenUpdating = True
err_handler:
NewName = ThisWB.Path & "\" & NewBook.Worksheets("Foglio1").Range("A4").Value & "_Summary(error).xls"
NewBook.SaveAs Filename:=NewName
NewBook.ActiveSheet.Range("A1").Select
NewBook.Close
Application.ScreenUpdating = True
End Sub

Excel- VBA PasteSpecial Method of Range Class Failed

Excel macro is intended to copy a range from one workbook to another using FileToOpen. The same code worked earlier today in separate workbook.
Error generated is Runtime 1004' PasteSpecial Method of class failed. Here's the section that fails:
SrcWB.Worksheets("1").Range("A1:K35").Copy
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteValues)
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteFormats)
Error gets caught on both PasteSpecial Values and Formats. I also tried to using:
SrcWB.Worksheets("1").Range("A1:K35").Value = TgtWB.Sheets("1").Range("A1:K35")
Above method didn't create any errors, however no values were transferred to the target workbook.
I've chewed on this most of this afternoon and would appreciate any help!
Here's the full code:
Sub CopySch()
Dim sh As Worksheet
Dim TgtWB As Workbook
Dim SrcWB As Workbook
Application.EnableEvents = False
Application.ScreenUpdating = False
Set TgtWB = ThisWorkbook
FileToOpen = Application.GetOpenFilename(FILEFILTER:="Excel Workbooks (*.xls*),*.xls*", Title:="Please select a file")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set SrcWB = Workbooks.Open(FileToOpen, xlUpdateLinksNever, ReadOnly:=True)
SrcWB.Worksheets("1").Range("A1:K35").Copy
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteValues)
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteFormats)
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
SrcWB.Close
End Sub

Goto the top of your module and add "Option Explicit".
Option Explicit
Sub CopySch()
Dim sh As Worksheet
Dim TgtWB As Workbook
Dim SrcWB As Workbook
...
It should solve your problem.
EDIT:
lets give another try with this code. i have tried the code it Works without error.
Option Explicit
Sub CopySch()
Dim sh As Worksheet
Dim TgtWB As Workbook
Dim SrcWB As Workbook
Dim FileToOpen As String
Application.EnableEvents = False
Application.ScreenUpdating = False
Set TgtWB = ThisWorkbook
FileToOpen = Application.GetOpenFilename(FILEFILTER:="Excel Workbooks (*.xls*),*.xls*", Title:="Please select a file")
If FileToOpen = "False" Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set SrcWB = Workbooks.Open(FileToOpen, xlUpdateLinksNever, ReadOnly:=True)
SrcWB.Worksheets("1").Range("A1:K35").Copy
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteValues)
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteFormats)
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
SrcWB.Close
End Sub