Refresh all on all open worksheets - excel

I have master sheet in which data from various "options" sheets pulled now I want to refresh all "options" sheets to get refresh on specific interval for that I have following vba code in master sheet
Public interval As Double
Sub Dosomething()
Dim xSh As Worksheet
Application.ScreenUpdating = False
For Each xSh In Worksheets
xSh.Select
Call macro_timer
Next
Application.ScreenUpdating = True
End Sub
Sub macro_timer()
interval = Now + TimeValue("00:03:00")
Application.OnTime interval, "my_macro"
End Sub
Sub my_macro()
For Each wb In Application.Workbooks: wb.RefreshAll: Next wb
Call macro_timer
End Sub
However code is not working as I wanted somewhere I am lacking, don't know where. pls help.thx

You could try:
Loop all open workbooks
Refresh
Code:
Option Explicit
Sub LoopOpenWorkbook()
Dim wb As Workbook
For Each wb In Application.Workbooks
wb.RefreshAll
Next wb
End Sub

Related

How to Make Destination Workbook Dynamic When Moving Data From Another User Selected File Using A VBA Macro in Excel

I'm attempting to have a user select a file, then through a UserForm select the worksheet they want to copy from.
The issue is on this line: ReportWbk.Sheets(ws).Cells.Copy Destination:=TargetWbk.Sheets("Test Import").Cells(1, 1)
I have confirmed that the file, worksheet selection, and copy function all work as expected. I get a run-time error '9': Subscript out of range. which to me means that the code is looking for the destination sheet in the workbook that the user selected (the 'target' file). Since it doesn't exist there, it errors out.
I'm wondering how to fix this dynamically so that the code will work without naming the workbook specifically. I might run this with other workbooks open and in different workbooks.
I verified that workbooks("WorkbookName").Sheets("Test Import").Cells(1, 1) works as I want but I'm looking to make the "WorkbookName" part dynamic / automatically select the workbook that the macro was run from.
The main code is directly below and the userform code is below that in case that's part of the issue:
Private Sub GetRange()
Dim ReportWbk As Workbook 'workbook with report data
Dim Report As Integer 'name of file with report data
Dim FD As FileDialog
Dim TargetWbk As Workbook 'this workbook
Dim ws As Variant
Set TargetWbk = ThisWorkbook
Set FD = Application.FileDialog(msoFileDialogFilePicker)
Report = FD.Show
'cancel pressed
If Report <> -1 Then Exit Sub
'open selected workbook
Set ReportWbk = Workbooks.Open(FD.SelectedItems(1))
ws = SelectSheet.Selection(ReportWbk)
'cancel pressed
If ws = vbCancel Then GoTo exitsub
ReportWbk.Sheets(ws).Cells.Copy Destination:=TargetWbk.Sheets("Test Import").Cells(1, 1)
exitsub:
ReportWbk.Close False
'changes the color of the destination worksheet tab
Worksheets("Test Import").Tab.Color = RGB(25, 25, 25)
End Sub
UserForm Code:
Private Sub cmdOK_Click()
Me.Tag = Me.ListBox1.Value
Me.Hide
End Sub
Private Sub cmdCancel_Click()
Me.Tag = vbCancel
Me.Hide
End Sub
Function Selection(ByVal wb As Object) As Variant
Dim ws As Worksheet
For Each ws In wb.Worksheets
'add all sheets to listbox
Me.ListBox1.AddItem ws.Name
Next ws
'default - select first sheet in list
With Me.ListBox1
.ListIndex = 0
.MultiSelect = fmMultiSelectSingle
End With
Me.Show
'return result
Selection = Me.Tag
Unload Me
End Function
Private Sub UserForm_Initialize()
Me.Caption = "Select Sheet"
Me.CmdOK.Caption = "OK"
Me.cmdCancel.Caption = "Cancel"
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
'disable X closing form
Cancel = CBool(CloseMode = 0)
If Cancel = -1 Then Me.Tag = vbCancel: Me.Hide
End Sub
I know this is a simple thing but I've been away from VBA for a few years and rusty as heck. Many thanks in advance!

UserForm: Stop execution of code, but let user look through workbooks?

I'd like to show a UserForm, but allow the user to look through worksbooks and worksheets. I know I can hide the UF, but I'd prefer to leave up the UF. Is this possible? I know there's vbModeless, but the code continues to execute, which is not what I want.
My code so far looks somewhat like this:
Sub Test()
Dim Counter As Long
Dim wb As Workbook
Application.ScreenUpdating = False
'-------main code
If Counter <> 0 Then
frmTest.Show
End If
Unload Me
For Each wb In Application.Workbooks
If wb.Name Like "Report*" Then wb.Close SaveChanges:=True
Next wb
Application.ScreenUpdating = True
End Sub
I could change the if-statement to
If ErrorCount > 0 Then
frmTest.Show vbModeless
Else
Call SaveWorkbooks
End If
Application.ScreenUpdating = True
End Sub
And create another sub:
Sub SaveWorkbooks()
Dim wb As Workbook
Unload frmTest
For Each wb In Application.Workbooks
If wb.Name Like "Report*" Then wb.Close SaveChanges:=True
Next wb
End Sub
I guess that works, but
Is it good practice splitting up your code like that?
What if this occurred in the middle of my main sub? That would make 1) even worse.
Is there a more elegant solution

Open and close UserForm multiple times without showing it's workbook

I've created a workbook that only shows a UserForm when it runs with the following code
Private Sub Workbook_Open()
Application.Visible = False
UserForm1.Show
End Sub
When the UserForm is initialized, it opens another workbook (WHITEBOOK.xls). After data has been entered into the form and the user clicks the Submit button, the data is inserted into this workbook that has been opened (I've omitted that code, but it works)
Private Sub UserForm_Initialize()
Set wb = Workbooks.Open("S:\!Data Tracking\WHITEBOOK.xls")
wb.Sheets("Jobs with Correct Template").Activate
If IsEmpty(wb.Worksheets("Jobs with Correct Template").Range("A3").Value) = True Then
Set SheetNameCellRange = wb.Worksheets("Jobs with Correct Template").Range("A2")
Else
wb.Worksheets("Jobs with Correct Template").Activate
Set SheetNameCellRange = wb.Worksheets("Jobs with Correct Template").Range("A2", Range("A2").End(xlDown))
End If
End Sub
When the user closes the UserForm, I close the form with this code, and close the UserForm's workbook also.
Private Sub UserForm_Terminate()
Unload Me
For Each wb In Application.Workbooks
If (StrComp(wb.Name, "Whitebook Data Entry (Final).xlsm", vbTextCompare) = 0) Then
wb.Close
End If
Next
End Sub
The problem I'm having is that I can't open the UserForm if the WHITEBOOK.xls workbook is already opened. I get a Run-time error '9': Subscript out of range and it fails at this line of the UserForm_Initialize() Sub.
wb.Sheets("Jobs with Correct Template").Activate
I've tried adding a conditional when I open the WHITEBOOK workbook to check if it is already open, and if so, to make it active, but I keep running into the same issue.
The code I used to test if the workbook is open was
Private Sub UserForm_Initialize()
Dim wkb As Workbook
On Error Resume Next
Set wkb = Application.Workbooks("S:\!Data Tracking\WHITEBOOK.xls")
If wkb Is Nothing Then
Set wb = Workbooks.Open("S:\!Data Tracking\WHITEBOOK.xls")
Else
wb.Sheets("Jobs with Correct Template").Activate
End If

excel 2007 Workbook_open not working

I am trying to clear Print Area And Autofilter when excel opens:
Am total novice in Excel vba so Assmebled the followingcode from googling around
This code I have put in ThisWorkbook of Personal.xlsb in the XLstart folder and ofcourse the macro security has been set to enable all macros
Option Explicit
Public WithEvents xlApp As Excel.Application
Private Sub Workbook_Open()
Set xlApp = Application
End Sub
Private Sub Workbook_Close()
Set xlApp = Nothing
End Sub
Private Sub xlApp_WorkbookOpen(ByVal Wb As Workbook)
Application.EnableEvents = False
Call ClrPrntArea
Application.EnableEvents = True
End Sub
Here is the ClrPrntArea
Sub ClrPrntArea()
Dim ws As Object
For i = 1 To ActiveWorkbook.Worksheets.count
With Worksheets(i)
.PageSetup.PrintArea = ""
.PageSetup.FitToPagesWide = 1
End With
Next
End Sub
I will also be putting another macro call to module in personal xlsb for resetting the autofiter once above starts working..Any inputs will be really helpfull
in PERSONAL.xlsb, module ThisWorkbook, try the below; it's nearly the same code as in your request, with some modif's:
application object declared Private
event routine uses the local WB object variable handed over as parameter, instead of the ActiveWorkbook object
replaced For ... Next by For Each ... Next and working with local object variables
trap processing of PERSONAL.xlsb itself
Once you're happy remove all the MsgBox statements (and the Else), they are just to show what is happening and when.
Private WithEvents Excel_App As Excel.Application
' runs when Excel_App encounters a Workbook_Open() event
Private Sub Excel_App_WorkbookOpen(ByVal WB As Workbook)
Dim WS As Worksheet
If WB.Name <> "PERSONAL.xlsb" Then
MsgBox "PERSONAL.xlsb: Excel_App_WorkbookOpen(): " & WB.Name
For Each WS In WB.Worksheets
WS.PageSetup.PrintArea = ""
WS.PageSetup.FitToPagesWide = 1
If WS.FilterMode Then
WS.ShowAllData
End If
Next
Else
MsgBox "PERSONAL.xlsb: Excel_App_WorkbookOpen(): myself"
End If
End Sub
' runs when PERSONAL.xlsb is opened
' assign current Excel application to object variable Excel_App
Private Sub Workbook_Open()
MsgBox "PERSONAL.xlsb: Workbook_Open()"
Set Excel_App = Application
End Sub
Note:
When the event handler doesn't start when you double-click an Excel file (e.g. on your desktop), close all Excel applications and inspect the task manager for additional orphaned Excel processes which need to be killed. It happened to me while playing around with this code

Set Workbook Variable from Userform Combobox

I am creating a macro for my co-workers. They get a file daily and at the end of the day have to copy certain information to another workbook. The macro is to take care of the copying. I want to have a userform with a combobox popup that contains a list of current open workbooks so it knows which file to copy from. How do I set it up so that the selection made there sets a workbook variable with that selection?
What I'm trying to do is:
Sub CopySub()
Dim wb As Workbook
UserForm1.Show
Set wb = Workbooks(ComboBox1.Value)
....Rest of Copy and Paste Code
Below is the code for the userform:
Private Sub OK_Click()
'Take user selection and continue copy and paste code
UserForm1.Hide
End Sub
Private Sub Cancel_Click()
'Cancel everything, end all code
End
End Sub
Private Sub UserForm_Activate()
'Populate list box with names of open workbooks.
Dim wb As Workbook
For Each wb In Workbooks
ComboBox1.AddItem wb.Name
Next wb
End Sub
Your code isn't working now because CopySub doesn't know what\where ComboBox1 is. Also, if the user clicks the form's X to close it instead of pressing the cancel button or clicks the OK button without selecting a workbook, CopySub will keep running.
There are a couple different ways to get the form information. The simplest with your current code is to properly reference ComboBox1 and add a simple test.
Sub CopySub()
Dim wb As Workbook
UserForm1.Show
If UserForm1.ComboBox1.Value = "" Then
Exit Sub
End If
Set wb = Workbooks(UserForm1.ComboBox1.Value)
' rest of code goes here
End Sub
Something else to think about though is ways to make your macro quicker and easier to run. If the only thing on your form is a Combobox for selecting the workbook and users will be starting the macro from a keyboard-shortcut or from the menu, consider having the macro ask if they want to run the macro on the active workbook. Clicking Yes to a question is a lot faster than having to click a dropdown box, select the workbook, and then click OK.
Sub CopySub()
Dim wb As Workbook
If MsgBox("Do you want to run the macro on '" & ActiveWorkbook.Name & "'?", vbQuestion + vbYesNo) = vbYes Then
Set wb = ActiveWorkbook
Else
UserForm1.Show
If UserForm1.ComboBox1.Value = "" Then
Exit Sub
End If
Set wb = Workbooks(UserForm1.ComboBox1.Value)
End If
' rest of code goes here
End Sub
After further searching I found the answer, and its the same as what mischab points out, I didn't create a global variable so there was no way for my userform to communicate with the subroutine. I solved this by declaring a variable with scope for the whole workbook as such:
Public wb1 As String
Sub CopySub()
Dim wbCAR As Workbook
UserForm1.Show
Set wbCAR = Workbooks(wb1)
....Rest of code
and by setting the userform code to such:
Private Sub OK_Click()
wb1 = ComboBox1.Value
UserForm1.Hide
End Sub
Private Sub Cancel_Click()
Unload Me
End
End Sub
Private Sub UserForm_Activate()
'Populate list box with names of open workbooks.
Dim wb As Workbook
For Each wb In Workbooks
ComboBox1.AddItem wb.Name
Next wb
End Sub

Resources