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
Related
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
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
I want to set ActiveWorkbook to a variable When workbook opens simultaneously ActiveWorkbook assign to a variable and that variable i can use in whole VBA excel project.
I tried to assigned in ThisWorkbook excel object on Workbook_open() function but it does not work.I provide that code below.
Private Sub Workbook_Open()
On Error Resume Next
Set WRBK = ActiveWorkbook
#If Mac Then
#Else
'unprotectVBProjProp
UnlockVBA ' Sujith ID: 12482
AddReferences ' Sujith ID: 12482
' protectVBProjProp
#End If
'MsgBox "xla Workbook opened"
Set eventInstance = New bwEvents
End Sub
So how can i set activeworkbook to a variable??
I am not so sure what are all the commands in the middle, like #If Mac Then , and UnlockVBA.
If you want to set the ActiveWorkbook to object WRBK, you will need to define WRBK in a regulare module as Public, and then use something like the code below:
Code in ThisWorkbook Module
Private Sub Workbook_Open()
Set WRBK = ActiveWorkbook
TestWorkbookName ' call sub <-- this is just to test the the workbook was assigned correctly
End Sub
Code in Regular Module
Option Explicit
Public WRBK As Workbook
Sub TestWorkbookName()
MsgBox WRBK.Name
End Sub
I'm running a word macro that
initializes Excel
creates a temporary workbook in excel
when exiting the word userform, terminates excel
However, it seems there is some residual Excel instances/workbook that is not fully closed because when I start the word macro again, I get error: 462, remote server machine ...
initialize userform in a word document:
private sub commandbutton1_click()
dim exc as excel.application
set exc as new excel.application
dim wb as excel.workbook
set wb = exc.workbook.saveas filename:="wordexc" 'creates temp workbook
userform1.show
end sub
run excel processing via a userform1 commandbutton:
private sub commandbutton2_click()
excel.workbook("wordexc").close 'closes temp workbook
dim wb as excel.workbook
set wb = excel.workbook.saveas filename:="wordexc" 'this wb is for actual use
'i do not delete this wb after running cuz it has stored data that will be used
'if user cliks commandbutton2 again, it will be deleted and new wbook with new data
'is created
'processing code
end sub
private sub queryclose (etc...)
'Close Excel
Dim sKillExcel As String
sKillExcel = "TASKKILL /F /IM Excel.exe"
Shell sKillExcel, vbHide
end sub
btw i think the problem is the last part:
Dim sKillExcel As String
sKillExcel = "TASKKILL /F /IM Excel.exe"
Shell sKillExcel, vbHide
Cuz if I stop the macro and terminate EXCEL in task manager, it doesn't give me this problem if I run the macro again...
i
I also tried other methods, like calling a excel workbook i saved in a directory instead of a temporary one via createobject("excel.application") in one sub, exc.quit, but I have to use that termination code above cuz otherwise EXCEL still shows in task manager.
Besides not declaring your objects correctly, you are not (if I may say so) flushing the toilet correctly.
See this example (UNTESTED)
I am using Latebinding instead of Early Binding so that this code is compatible with any version of Excel
'~~> Define your Excel objects so that they are available
'~~> in other userform sub procedures as well.
Dim oXLApp As Object, oXLwb As Object
Private Sub CommandButton1_Click()
Set oXLApp = CreateObject("Excel.Application")
'~~> Show Excel
oXLApp.Visible = True
'~~> Add a new workbook
Set oXLwb = oXLApp.Workbooks.Add
'
'~~> Do some stuff
'
'~~> Save the file
oXLwb.SaveAs "C:\wordexc.xlsx", FileFormat:=51
oXLwb.Close SaveChanges:=False
End Sub
'~~> Close and Quit Excel (Flush Toilet)
Private Sub CommandButton2_Click()
oXLApp.Quit
Set oXLwb = Nothing
Set oXLApp = Nothing
End Sub
Why not do something like this? Basically, you define your excel object globally, and then you can call it's "Quit" method later.
Private objExcel As Excel.Application
Private Sub CommandButton1_Click()
Set objExcel = New Excel.Application
objExcel.Visible = True
End Sub
Private Sub CommandButton2_Click()
objExcel.Quit
End Sub
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