Quit MS Access without compacting, even though "Auto Compact" is set - vba

We have numerous MS Access files with the "Auto Compact" option set.
I would like to open a file using VBA and close it (or quit) without going through the long compacting process. However, I don't want to touch the "Auto Compact" option, because it needs to stay True for the normal users.
Is it possible to close the file with VBA and skip the compacting?

You can always disable the Auto Compact on Close and use a Flagging system. Create a Universal flag, allowCompact As Boolean, and based on the user permission set the Flag to True, and on a Form (probably a hidden form) or the form that is always kept open's Close method you can check if the Compact Flag is set, if yes use the Code (http://access.mvps.org/access/general/gen0041.htm) to Perform Compact else just quit the DB.
'In a Standard Module
Public allowCompact
'Code to perform AutoComapct
Public Sub CompactDB()
CommandBars("Menu Bar"). _
Controls("Tools"). _
Controls("Database utilities"). _
Controls("Compact and repair database..."). _
accDoDefaultAction
End Sub
Then in the Form that is opened first (probably a login Form)
Private Sub buttonName_Click()
'Check the users permission
If Me.permissionLevel <> "Manager" Then
allowCompact = True
Else
allowCompact = False
End If
End Sub
Then finally on the Final form's close event you can use.
Private Sub Form_Close(Cancel As Integer)
If allowCompact Then _
CompactDB
Application.Quit
End Sub
Hope this helps !

Related

How to enable the startup options in an Access database project using Shift Key?

I disabled the startup options of my access project(.accdb) using this code from Microsoft. And it worked after I type in the immediate window to disable to shift key.
But how can I re enable the shift key again since I cannot go through with the code anymore since it is now hidden and all I can see now is this.
Any idea how can I view the immediate window again to enable the shift key?
Enable Bypass key from VBA code in another database. This will be the only way if also disabled special keys like Alt-F11. Here is modified code from Microsoft site. Create this function in another database and modify path to your protected database:
Function ap_EnableShift()
'This function enables the SHIFT key at startup. This action causes
'the Autoexec macro and the Startup properties to be bypassed
'if the user holds down the SHIFT key when the user opens the database.
On Error GoTo errEnableShift
Dim db As DAO.Database
Dim prop As DAO.Property
Const conPropNotFound = 3270
Set db = OpenDatabase("C:\path\tst.accdb")
'This next line of code enables the SHIFT key on startup.
db.Properties("AllowByPassKey") = True
'function successful
Exit Function
errEnableShift:
'The first part of this error routine creates the "AllowByPassKey
'property if it does not exist.
If Err = conPropNotFound Then
Set prop = db.CreateProperty("AllowByPassKey", _
dbBoolean, True)
db.Properties.Append prop
Resume Next
Else
MsgBox "Function 'ap_DisableShift' did not complete successfully."
Exit Function
End If
End Function

How to Edit a Read-Only Word Document (VBA)

I am periodically getting Word documents from various clients and sometimes they send them to me in 'Read-Only' mode. While it isn't a big deal to go to 'View > Edit Document' manually, I cannot seem to find how to do this within my VBA code.
Either opening a document as editable or toggling it as editable once it is open would be sufficient for my needs.
Note that I cannot open the document with 'readOnly = false' as it looks like it is set to 'readOnly recommended' (based on my reading of the MS man page on Document.Open).
IN CONTEXT:
I was also hitting a problem with turning off 'read-mode' which the documents were opening as by default. I have posted this question and answer here.
The code below will change the ReadOnly attribute of a closed file, setting its ReadOnly attribute to either True or False depending on the argument supplied to the procedure.
Private Sub SetReadOnlyProperty(Fn As String, _
ByVal ReadOnly As Boolean)
' 21 Nov 2017
Dim Fso As Object
Dim Doc As Object
Set Fso = CreateObject("Scripting.FileSystemObject")
Set Doc = Fso.GetFile(Fn)
If (Doc.Attributes And vbReadOnly) <> Abs(Int(ReadOnly)) Then
Doc.Attributes = Doc.Attributes Xor vbReadOnly
End If
End Sub
This procedure requires access to the MS Scripting Runtime DLL. Enable this access by checking the box against Miscrosoft Scripting Runtime from Tools >References in the VBE window. Below is an example of how to call the function. Note that an error will result if the supplied file doesn't exist.
Private Sub TestReadOnly()
SetReadOnlyProperty "H:\Test Folder\Test File.docx", False
End Sub

Excels "Refresh All" sometimes not working

I have a VBA function that opens a file, refreshes all the data connections, saves the file and the returns "true" if the refresh was successful. Here is the code:
Public Function RefreshFile(ByVal wbName As String, ByVal FilePath As String, ByVal pword As String)
Dim blTmp As Boolean
Dim wbRefresh As Workbook
blTmp = Not (IsWorkBookOpen(FilePath))
If blTmp Then
Workbooks.Open Filename:=FilePath, ReadOnly:=False, Notify:=False, WriteResPassword:=pword, IgnoreReadOnlyRecommended:=True
Else
RefreshFile = False
Exit Function
End If
Set wbRefresh = Workbooks(wbName & ".xlsx")
wbRefresh.Activate
ActiveWorkbook.RefreshAll
DoEvents
'MsgBox "complete"
wbRefresh.Close savechanges:=True
RefreshFile = True
End Function
The list opens a series of files and some are password protected and read-only suggested (hence the parameters passed). With the read-only suggested files though, files get saved with only one of the connections refreshed. Basically it refreshes the first connection and then saves the file.
I've tested this a number of times and if I stop the function after 'DoEvents' (notice the MsgBox to stop the code), then all the connections are in fact refreshed. If I don't stop the code and reopen the saved file later on, only one of the connections get refreshed. Is this an issue with 'RefreshAll' or when it goes to save the file? Perhaps I'm not opening the file with the full, appropriate permissions??
The solution is that 'enable background refresh' needs to be unchecked on each data table. Don't ask me what exactly this means, but after a lot of trial/error, I finally got it to work by unchecking the 'enable background refresh' option on the data connections for the data tables.
I looked at this myself, and when looking at the "enable background refresh", I noticed there is a button for "Refresh this connection on Refresh All". So I had to tick this for it to work for me.

Access 2013 - Save Value from Textbox and display again when form is opened after close

I want to save a value from textbox in a string for example and display it again when the form get's openend.
I have two textboxes PriceRangeOne and PriceRangeTwo .. The user enter here for example 20 and 40
The problem i have is that when the user switches between Form and Report the values in this textboxes are beeing deleted. How can i save them?
I tried adding a sourcecontrol to the fields but had name errors eventhough i used different names.
I tried adding this to on change and retrieve it in an onload
Dim eingabe As String = textBox1.Text or .Value
Still didn't worked. Does anyone know a way to do this?
Typically, the most efficient and reliable way to do this is to have some form auto-open when the database is opened. It could be a dashboard, or just some form with nothing else on it. Whatever you use, launch it when the database opens and then minimize it. Now you have a form that's always open, as long as the application is open. Add a couple of textboxes to this form/dashboard.
When you close your form referenced in this question, write the values of PriceRangeOne and PriceRangeTwo to the textboxes on the form I described above. Then, when you open a new form or report, you can reference the values in those textboxes. Since the form is always open, you can reference these values at any time from any form or report until you close your database.
Solved it with variables.
I declared global variables in my standart module
For example
Public PriceOne As Double
Public PriceTwo As Double
Than i did this in my form in Close() and Open():
Private Sub Form_Close()
PriceOne = Me.Field
PriceTwo = Me.FieldTwo
End Sub
Private Sub Form_Open(Cancel As Integer)
Me.Field = PriceOne
Me.FieldTwo = PriceTwo
End Sub
Works perfect!
Courtesy of How to save the last value of a textbox. | Access World Forums:
Private Sub Form_Close()
'Set the default value for textbox
DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE table SET table.field = [Forms]![FormName]![Textbox] " & vbCrLf & _
"WHERE (((table.ID)=1));"
DoCmd.SetWarnings True
End Sub
Private Sub Form_Load()
'Load the default value for textbox
Me.Textbox.Value = DLookup("[field]", "[table]", "[ID]=1")
End Sub

Close modal form in Access and access module code

I've inherited a Access database that is used to import some data in SQL. The MDB opens with a form, in a modal mode: no Access menubar or buttons are visible. I can view the tables with content by using the Visual Studio 'Data Connection' tool, but I cannot see the module's code.
I've looked at this question here, but the answers there aren't really what I need. Is there a way to either force the form to close (and access the modules) or to extract the VBA code ?
[EDIT] I am using Access 2007, not sure what the original developer used.
Hold down the shift key when you open the database. This will prevent it from loading the automatic script it's running and allow you to gain access to the tables, queries, and VBA scripts.
This is a rather long addendum to, or comment on, Michael Todd's reply in response to edosoft's comment.
Rather than choosing to enable the content, check the start-up options (either (file->options->current database->display form) or (tools->start up->display form)) and remove the name of the form, having taken a note, and ensure that Allow Full Menus (same page) is ticked. You may also like to press Alt+F11 to display code, and check that for start-up code, finally, see if there is an AutoRun macro and rename it.
EDIT re Comments
You do not have to open an mdb to change the start-up form, for example, code such as this could be run from another mdb using the full name and path of the mdb you wish to change.
Sub SetStartForm(DBFile As String)
Dim prp As Object
Dim db As Database
Const PROPERTY_NOT_FOUND As Integer = 3270
Set db = OpenDatabase(DBFile)
db.Properties("StartupForm") = "(none)"
If Err.Number > 0 Then
If Err.Number = PROPERTY_NOT_FOUND Then
'' Create the new property, but this is not relevant in this case
End If
End If
db.Close
Set db = Nothing
Set prp = Nothing
End Sub
Button close with function:
Private sub cmdClose_Click()
CloseForm(YourFormName)
End sub
Public Sub CloseForm(ByVal strFormName As String)
Dim iCounter As Integer
For Each frm In Forms
With frm
If (.Name = strFormName) Then
iCounter = iCounter + 1
End If
End With
Next
If (iCounter > 0) Then
For i = 1 To iCounter
DoCmd.Close acForm, strFormName, acSaveNo
Next
End If
End Sub