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

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

Related

Delete a Worksheet upon Exit (if it exists) VBA

I am attempting to delete a worksheet from this Excel file upon exit (if it exists). The code I have tells it to automatically delete the sheet and say "yes, delete" in the popup box, but it is not running for some reason.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'
' This procedure will delete sheet upon exit and select "Yes, Delete" in the
' pop-up box
'
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.Name = "Temp" Then
Application.DisplayAlerts = False
Worksheets("Temp").Delete
Application.DisplayAlerts = True
End If
Next
End Sub
You may try something like this...
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim ws As Worksheet
Application.DisplayAlerts = False
On Error Resume Next
Set ws = Sheets("Temp")
If Not ws Is Nothing Then
ws.Delete
ThisWorkbook.Save
End If
Application.DisplayAlerts = True
End Sub
I think you should code
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
On Error Resume Next ' this will prevent subsequent line from stoping code should there be no "Temp" sheet
Sheets("Temp").Delete
Application.DisplayAlerts = True
Me.Save ' be sure you save the workbook before closing it
End Sub

VBA Deleting blank worksheets where the worksheets have been renamed in Spanish?

I am working with a file where the worksheets have been renamed. Instead of Sheet1(generic name) it is Hoja1(generic name).
Wondering if this is stopping my code from working.
My code is very simple. I dont know what other error I could be having.
Sub Macro1()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Application.DisplaysAlerts = False
If LenB(ActiveSheet.Range("A5")) = "" Then ActiveSheet.Delete
Application.DisplayAlerts = True
Next ws
End Sub
Thank you.
If it's definitely going to have "Hoja" in the sheet name, this should work.
Sub Macro1()
Dim WS As Worksheet
Application.DisplayAlerts = False
For Each WS In ActiveWorkbook.Sheets
If InStr(WS.Name, "Hoja") <> 0 Then WS.Delete
Next
Application.DisplayAlerts = True
End Sub
Got some help from someone.
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Application.DisplayAlerts = False
If LenB(ws.Range"A5")) = 0 Then ws.Delete
Application.DisplayAlerts = True
Next ws
The spanish wasn't the issue.
To get the name Hoja1 if the sheet appears as Hoja1(1) in the VBA browser you can use the .CodeName property:
'code borrowed from Alex's answer
Sub Macro1()
Dim WS As Worksheet
Application.DisplayAlerts = False
For Each WS In ActiveWorkbook.Sheets
If InStr(WS.CodeName, "Hoja") <> 0 Then WS.Delete
Next
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

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

Save Selected Sheets to a different work book in VBA

I would like to save a number of worksheets from the current workbook to a different workbook and exclude a sheet named "buttons" (in current one) from that saving process.
Can anybody help please? The number of worksheets is changeable FYI.
Below is what I have so far which include all the sheets from current workbook.
Sub SaveAs()
D1 = VBA.Format(Now, "mm_DD_yyyy")
For Each ws In Application.Workbooks
ws.SaveAs Filename:="C:\Users\e2309\Desktop\Andy's\GBB_Report_" & D1 & ".csv"
Next ws
Application.Quit
End Sub
Or more directly
copy the entire workbook
delete the redundant sheet
code
Sub Simpler()
Dim wb As Workbook
Dim strFile As String
strFile = "C:\temp\yourfile.xlsm"
ThisWorkbook.SaveAs strFile, xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = False
ThisWorkbook.Sheets("buttons").Delete
Application.DisplayAlerts = True
End Sub
This might get you a little closer. Note this is not complete and very untested.
Sub work()
Dim WB As Workbook
Dim Nwb As Workbook
Dim WS As Worksheet
Set Nwb = New Workbook
Set WB = ThisWorkbook
For Each WS In WB.Sheets
If WS.Name <> "Don't copy" Then
WS.Copy Nwb.Sheets("sheet1")
End If
Next
Nwb.Save
End Sub