Unshare workbook everyday - vba

I want to unshare a excel workbook everyday at 11:00pm.
First I use windows task scheduler to open the file at 10:59:45pm, and then run the following code.
Would the following code work?
Sub Unshare()
Application.DisplayAlerts = False
If ThisWorkbook.MultiUserEditing Then
ThisWorkbook.ExclusiveAccess
Application.DisplayAlerts = True
ThisWorkbook.Close
Else
Application.DisplayAlerts = True
ThisWorkbook.Close
End Sub
Sub Workbook Open()
Application.OnTime TimeValue("23:00:00"), "Unshare"
End Sub
Also, all of the code is located in Thisworkbook.
Thanks!

Try using Workbook_Open event in the private module of the Workbook object.
Private Sub Workbook_Open( )
Application.OnTime TimeValue("23:00:00"), "Unshare"
End Sub

Related

Close another workbook upon closing the workbook

I have a code that opens another workbook (source.xlsx) when I open (triggers on Workbook_Open event) a template workbook (template.xlsm).
The code:
Private Sub Workbook_Open()
Application.Screenupdating= False
Set w = workbooks
w.open filename:="link", Updatelinks:=true , readonly:=true
activewindow.visible=false
thisworkbook.activate
application.screenupdating=True
end sub
However, I want the source workbook to just run on background upon opening and close it when I close the template file.
Private sub workbook_aftersave()
Workbook("source.xlsx").Close SaveChanges:=False
End Sub
You want to use the Workbooks collection (Workbooks("source.xlsx")), rather than a Workbook object (Workbook("source.xlsx"), which will throw an error). Also, rather than trying to close it on the Workbook_AfterSave event, you could try using the Workbook_BeforeClose event:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error Resume Next 'In case the Workbook is already closed
Workbooks("source.xlsx").Close SaveChanges:=False
End Sub
{EDIT} And, because I can, here's a tidier version of your Workbook_Open code too:
Private Sub Workbook_Open()
Application.ScreenUpdating = False
Dim wsSource As Workbook
Set wsSource = Workbooks.Open(Filename:="SomeDirectory\source.xlsx", UpdateLinks:=True, ReadOnly:=True) 'Change the filename to where your "source.xlsx" is stored
DoEvents 'Wait for it to finish opening
wsSource.Windows(1).Visible = False
ThisWorkbook.Activate
Application.ScreenUpdating = True
End Sub
Try using
Application.Visible = False
Place this in your Workbook_Open code on the workbook you want to hide, and then use True to bring it back to close.

how to display only userform in vba excel?

I have a userform which is created in vba and I want to display only the userform when I open my excel... is there a way to do this.. I have already tried the codes such as
application.visible = false , activewindow.visible= false
if I use this codes in the module before open the files which are already open will b hidden along with the file which I am opening
can someone tel me how can i particularly hide the file which I want to open and display the userform
Try something like this
1- Create a user form with 2 button (see below pic)
2- ThisWorkbook code
Private Sub Workbook_Open()
UserForm1.Show vbModeless
End Sub
3- Form code
Private Sub CommandButton1_Click()
If Workbooks.Count > 1 Then
Windows("Test.xlsm").Visible = True
Else
Application.Visible = True
End If
End Sub
Private Sub CommandButton2_Click()
If Workbooks.Count > 1 Then
Windows("Test.xlsm").Visible = False
Else
Application.Visible = False
End If
End Sub
Private Sub UserForm_Initialize()
If Workbooks.Count > 1 Then
Windows("Test.xlsm").Visible = False
Else
Application.Visible = False
End If
End Sub
Private Sub UserForm_Terminate()
If Workbooks.Count > 1 Then
Windows("Test.xlsm").Visible = True
Else
Application.Visible = True
End If
End Sub
This will only show or hide the form's workbook. Any other workbooks opened will remain unaffected.
I think if you ensure that other workbooks are not open, that might solve the problem.
Private Sub Workbook_Open()
If Workbooks.Count > 1 Then
MsgBox "Close All excel files before running it"
ThisWorkbook.Close
Else
Application.Visible = False
frmmain.Show
End If
End Sub

How can I run an excel enabled event macro across all open sessions in excel?

VBA newbie here.
I have an excel spreadsheet that is locked for formatting. However, if you paste into the spreadsheet, the format copied is then pasted into the locked worksheet. I'm using the code below to create an event in excel to undo and paste special values.
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Application.CutCopyMode = xlCopy Then
Application.EnableEvents = False
Application.Undo
Target.PasteSpecial Paste:=xlPasteValues
Application.EnableEvents = True
End If
End Sub
This works perfectly, however, this only works if I am copying and pasting within the same excel session. How can I get this to work across all excel instances?
Thanks!
Dan
Paste this into the Thisworkbook module of the same file (assuming that moduleis currently empty!):
Option Explicit
Private WithEvents App As Application
Private Sub App_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Application.CutCopyMode = xlCopy Then
Application.EnableEvents = False
Application.Undo
Target.PasteSpecial Paste:=xlPasteValues
Application.EnableEvents = True
End If
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Set App = Nothing
End Sub
Private Sub Workbook_Open()
Set App = Application
End Sub

Hiding worksheet completely in favour of userform

I have a userform and would like this to be the first thing that is shown to the user when opening the workbook, and the sheet behind this form to be hidden.
I understand the below is the code to do this:
Private Sub Workbook_Open()
Application.Visible = False
UserForm1.Show vbModeless
End Sub
This performs the operation successfully, but my worksheet flashes up for a second or two before it is hidden and the userform appears.
This is long enough for someone to take a screenshot or see valuable information behind the userform.
It also doesn't look very tidy!
Is there a way to alter anything within the VBA to accomplish this?
I have discovered that it is possible with batch scripts or something similar but I have no experience of this and would prefer not to add another dimension to an already complex form.
I'd opt for a Workbook_BeforeClose event that hides all of the sensitive sheets. That way your data remains hidden to people opening your file without macros enabled.
This goes in a new standard module
Option Explicit
Option Private Module
Public Sub SheetsHidden(ByRef hidden As Boolean)
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name <> "Home" And hidden Then 'your *safe* sheet name
ws.Visible = xlSheetVeryHidden
Else
ws.Visible = xlSheetVisible
End If
Next ws
End Sub
And then you can call it from your ThisWorkbook module
Private Sub Workbook_BeforeClose(Cancel As Boolean)
SheetsHidden True
End Sub
Once you have authenticated the user you can unhide the sheets with the parameter as False.
I would also recommend exploring UserForms, particularly:
With New UserForm1
.Show vbModeless
'do more with your form
End With
By design, opening Excel file without Excel showing up is not possible without external script or tool.
Easier way to hide all sheets is to save the file as .xla(m) (or using ThisWorkbook.IsAddin = True)
Private Sub Workbook_Open()
ThisWorkbook.IsAddin = True ' True by default for .xla(m) Excel Add-In files
Application.Visible = Workbooks.Count
UserForm1.Show vbModeless
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not ThisWorkbook.IsAddin Then ThisWorkbook.IsAddin = True
If Not ThisWorkbook.Saved Then ThisWorkbook.Save
If Workbooks.Count Then Application.Visible = True Else Application.Quit
End Sub
and in the form close event:
Private Sub UserForm_Terminate()
If Workbooks.Count Then ThisWorkbook.Close True Else Application.Quit
End Sub

how can I have every excel workbook I open to have columns.autofit property?

I would like to write a macro or adjust Excel properties, so that whenever I open a new excel workbook all values are autofited to the columns.
I tried using the following code, which works if I save the code for a specific workbook, however if I save the code in the PERSONAL workbook, the code produces an error. "Method 'Columns' of object '_Global' failed"
Sub auto_open()
Columns().AutoFit
End Sub
The way I do this is to create a simple add-in that handles Application events I want to intercept. The reason that it doesn't work in the auto_open() is because you are trying to work with the Columns object before it gets instantiated. Much better to use the SheetActivate event. This also avoids the possibility of opening a Workbook with 20 pages and having to wait for all of them to AutoFit. You only see the active sheet, right?
The concept is to grab a reference WithEvents to the application and set up handlers to whatever events you care about. To do this, you'll have to put the code into a class. I called mine "AppHolder".
Class code:
Option Explicit
Private WithEvents app As Application
Private Sub Class_Initialize()
Set app = Application
End Sub
Private Sub app_SheetActivate(ByVal Sh As Object)
Sh.Columns().AutoFit
End Sub
Private Sub app_WorkbookActivate(ByVal Wb As Workbook)
Wb.ActiveSheet.Columns().AutoFit
End Sub
Private Sub app_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
Sh.Columns().AutoFit
End Sub
Then, create an instance of your class in and set it in auto_open (or Workbook_Open as the case may be) in the ThisWorkbook module:
Option Explicit
Private hook As AppHolder
Private Sub Workbook_Open()
Set hook = New AppHolder
End Sub
Save it as an Excel add-in file (.xlam) in the default location - should be in Users[You]\AppData\Roaming\Microsoft\AddIns. Close Excel and re-open it, then go to Developer...Add-Ins and enable it. All there is to it.
EDIT: Almost forgot - that doesn't cover all situations in which you'll be presented with a Worksheet. You need WorkbookActivate and WorkbookNewSheet too...
You could use something like this: (untested)
Sub auto_open()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.DisplayAlerts = False
Dim wb As Workbook
Dim ws As Worksheet
For Each wb In Workbooks
For Each ws In wb.Worksheets
ws.Columns.AutoFit
Next ws
Next wb
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Its important to identify the Objects you are working on (in this case workbooks and worksheets) because it helps you to know which method you could apply to them (see)
This might work :
Sub auto_open()
For i = 1 To Application.Workbooks.Count
For j = 1 To Application.Workbooks(i).Sheets.Count
For k = 1 To Application.Workbooks(i).Sheets(j).Cells(1, Columns.Count).End(xlToLeft).Column
Application.Workbooks(i).Sheets(j).Columns(k).EntireColumn.AutoFit
Next k
Next j
Application.Workbooks(i).Save
Next i
End Sub