VBA ThisWorkbook.SaveAs Filename:=SaveAsName custom name (SaveAsName) not appearing in dialog - vba

I'm hoping somebody can help me with this. I'm creating a model in Excel using VBA and want to populate the Save As dialog with a custom filename. I have three pieces of code. The first is for a userform that asks the end-user to enter the name of their facility:
Private Sub cmdNext_Click()
strHospName = frmHospName.txtHospName.Value
' Check for a usable hospital name
If Len(strHospName) = 0 Then
frmHospName.Hide
MsgBox "Please provide the name of your facility.", vbCritical + vbOKOnly, "Missing Facility Name"
frmHospName.Show
End If
If (Len(strHospName) - Len(Trim(strHospName)) = Len(strHospName)) Then
frmHospName.Hide
MsgBox "Please provide the name of your facility.", vbCritical + vbOKOnly, "Missing Facility Name"
frmHospName.Show
End If
If strHospName Like "*[\/:*?""<>|]*" Then
frmHospName.Hide
MsgBox "Please enter your facility's name without any of the following characters: \ / : * ? < > | ", vbCritical + vbOKOnly, "Invalid Facility Name"
frmHospName.Show
End If
Call SaveAsNameStore(strHospName, MyName)
Set currForm = Me
Unload Me
End Sub
The second piece lives in its own module and checks to see if this model has already been customized (a customized model will not see frmHospName upon workbook open, thus strHospName will not get assigned), and based on that check, it creates the string SaveAsName:
Public strHospName As String
Public SaveAsName As String
Function MyName() As String
MyName = ThisWorkbook.Name
End Function
Sub SaveAsNameStore(strHospName As String, MyName As String)
' This code creates a custom SaveAs name
Dim strModelDate As String
strModelDate = Format(Now, "mm-dd-yyyy")
If (Len(strHospName) - Len(Trim(strHospName)) = Len(strHospName)) Then
SaveAsName = MyName
Else
SaveAsName = strHospName & " customized economic model " & strModelDate
End If
End Sub
The third piece lives in ThisWorkbook and applies SaveAsName in Workbook_BeforeSave:
Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
''This code forces SaveAs with custom filename instead of Save to prevent overwriting the master model file
''NEED TO UNCOMMENT PRIOR TO DELIVERY
Application.ScreenUpdating = False
If SaveAsUI = False Then
Cancel = True
ElseIf SaveAsUI = True Then
With Application.FileDialog(msoFileDialogSaveAs)
Application.EnableEvents = False
If .Show Then
ThisWorkbook.SaveAs Filename = SaveAsName
End If
Application.EnableEvents = True
End With
Cancel = True
End If
End Sub
The problem is that, when I click the "Save As" button, the custom SaveAs name isn't populating in the dialog. I can see that SaveAsName is generated correctly via ?SaveAsName in the Immediate window. For syntax, I've tried both ThisWorkbook.SaveAs Filename = SaveAsName and ThisWorkbook.SaveAs Filename:=SaveAsName with the same result both times.
Sorry for the long-winded post. I would appreciate any help you can provide!

This is something I use to make a backup of something I'm currently working in, without naming it the same thing. Easily modified for your situation and variables
Private Sub cmdBackupButton_Click()
'__BACKUP THE CURRENT WORKBOOK___
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs "C:\WhateverPathYouWant\myFile_backup.xlsb")
Application.DisplayAlerts = True
End Sub
This eliminates any "save as" dialogue, and needs no interaction. Very simple.

Related

Access. How to Create a record and select that record in CBO on another form?

I have two forms frmProductCreate and frmColourCreate.
In frmProductCreate I have:
Combobox: colourID
Button: btnColCreate
The idea is that if a user needs to create a new colour, they can click on the create button which opens frmColourCreate, name the new colour and click save button. Which will save the new colour in the colours table (which is the record source for the cbo ColourID in frmProductCreate). Then requery colourID in frmProductCreate and close frmColourCreate.
What I also want this save button to do is after the requery to select the cbo colourID and go to the last created colour. i.e. the last record. I have tried a few codes but failed to make it work. Any help will be greatly appreciated.
Private Sub btnSavecol_Click()
Dim cancel As Integer
If Me.ColName = "" Then
MsgBox "You must enter a Colour Name."
DoCmd.GoToControl "ColName"
cancel = True
Else
If MsgBox("Are you sure you want to create new Colour?", vbYesNo) = vbNo Then
cancel = True
Else
CurrentDb.Execute " INSERT INTO Colours (ColName) VALUES ('" & Me.ColName & "')"
Me.ColName = ""
DoCmd.Close
If CurrentProject.AllForms("frmProductCreate").IsLoaded = False Then
cancel = True
Else
Forms!frmproductCreate!ColourID.Requery
'Forms!frmproductCreate!ColourID.SetFocus
'Forms!frmproductCreate!ColourID.items.Count = -1
'Forms!frmproductCreate!ColourID.Selected(Forms!frmproductCreate!ColourID.Count - 1) = False
'YourListBox.SetFocus
'YourListBox.ListIndex = YourListBox.ListCount - 1
'YourListBox.Selected(YourListBox.ListCount - 1) = False
End If
If CurrentProject.AllForms("frmProductDetails").IsLoaded = False Then
cancel = True
Else
Forms!frmproductDetails!ColourID.Requery
End If
End If
End If
End Sub
Some remarks:
Whatfor is the variable cancel? Because it is not used, I removed it.
I have no really idea whatfor you need Me.ColName = "".
Why do you close the current form so early? I moved DoCmd.Close to the end.
I made your code a bit more readable, by removing 'arrow-code' (those nested IFs).
Finally try this:
Private Sub btnSavecol_Click()
If Me.ColName.Value = "" Then
MsgBox "You must enter a Colour Name."
DoCmd.GoToControl "ColName"
Exit Sub
End If
If MsgBox("Are you sure you want to create new Colour?", vbYesNo) = vbNo Then Exit Sub
CurrentDb.Execute "INSERT INTO Colours (ColName) VALUES ('" & Me.ColName.Value & "')"
If Not CurrentProject.AllForms("frmProductCreate").IsLoaded Then GoTo Done
Forms!frmproductCreate!ColourID.Requery
'This sets the ComboBox 'ColourID' to the new colour:
'Forms!frmproductCreate!ColourID.Value = Me.ColName.Value
'If you use an automatic generated ID in the table 'Colours', then you will have to get that ID from the color and set it to the ComboBox:
Forms!frmproductCreate!ColourID.Value = DLookup("ColID", "Colours", "ColName = '" & Me.ColName.Value & "'")
Me.ColName.Value = ""
If Not CurrentProject.AllForms("frmProductDetails").IsLoaded Then GoTo Done
Forms!frmproductDetails!ColourID.Requery
Done:
DoCmd.Close
End Sub

MS Access VBA to enable / disable a text box

I have the below VBA code in access to enable/disable a text box.
When the code is executed the tonnes textbox remains disabled.
Am I missing an additional property?
Private Sub EnableTonnes()
Dim sCode As String
sCode ="xx"
' set default values for tonnes enabled and locked properties
Tonnes.enabled = False
Tonnes.Locked = True
If sCode = "xx" Then
' enable tonnes field
Tonnes.enabled = True
Tonnes.Locked = False
End If
End Sub
Your code looks ok. TextBox properties are set in form design mode and can only be permanently changed in form design mode. You do some sophisticated coding to open the form in design mode, change the properties and then save the form... or do it manually. You will always be able to use your code to control those properties at runtime.
Option Compare Database
Option Explicit
Private Sub cmdGo_Click()
Dim sCode As String
sCode = "xx"
' set default values for tonnes enabled and locked properties
txtTonnes.Enabled = False
txtTonnes.Locked = True
If sCode = "xx" Then
' enable tonnes field
txtTonnes.Enabled = True
txtTonnes.Locked = False
End If
MsgBox txtTonnes.Name & " Enabled status is " & txtTonnes.Enabled
MsgBox txtTonnes.Name & " Locked status is " & txtTonnes.Locked
End Sub
Private Sub Form_Load()
MsgBox txtTonnes.Name & " Enabled status is " & txtTonnes.Enabled
MsgBox txtTonnes.Name & " Locked status is " & txtTonnes.Locked
End Sub

BeforeClose will not close my Excel-Sheet VBA

So I have been trying to put together a little Excel sheet, that has an entry Log in it. So whenever the sheet is closed, Name, Date and Time are added.
So basically I have three macro running, I will only mention two. The main macro will ask if I want to close the sheet and I will have to answer with yes or no. This works fine. If I press yes the main macro will call a sub macro, that will ask me to enter a string. If this Inputbox is empty or the entry is canceled, I want the main sub to stop running and cancel the Close process. Which won't seem to work. The error in the code to me seems pretty clear, but I don't know how to prevent it and find a better solution. If you could help me come up with a solution I would really appreciate it.
This line of code seems to be the problem:
If Cancel_Button_LOG = False Then Cancel = True
Here I will add compressed versions of the two macros
Public Sub Add_Entry_to_Log()
Dim i As Integer
Dim response As Variant
Cancel_Button_LOG = True
response = InputBox("Please enter your Name", "Name")
If response <> "" Then
Else
Cancel_Button_LOG = False
MsgBox "Please enter your name", vbExclamation + vbOKOnly, "Name"
End If
Worksheets("Log").Protect "secret"
ThisWorkbook.Save
End Sub
Now I will want to use the Cancel_Button_log Variable to cancel the main sub:
Dim answer As Variant
answer = MsgBox("Are your sure you want to close the workbook?", vbYesNo) Cancel = False
Select Case answer
Case Is = vbYes
Worksheets("Log").Unprotect "secret"
Call Test
Call Add_Entry_to_Log
If Cancel_Button_LOG = False Then Cancel = True
Worksheets("Log").Protect "secret"
Case Is = vbNo
Cancel = True
End Select
ThisWorkbook.Save
End Sub
I think you're doing this in the most complicated way possible. If I understand your requirements correctly - you can replace all your code in your ThisWorkbook module with something like this:
Const WB_LOG As String = "Log" '// name of sheet that the log is in
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If MsgBox("Do you really want to close the workbook?", vbYesNo) = vbYes Then
With Sheets(WB_LOG)
.Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Resize(1, 2).Value = Array(Environ$("USERNAME"), Now)
End With
ThisWorkbook.Save
Else
Cancel = True
End If
End Sub
Private Sub Workbook_Open()
With Sheets(WB_LOG)
.Protect Password:="secret", UserInterfaceOnly:=True
.Range("A1:B1").Value = Array("USERNAME", "TIMESTAMP")
End With
End Sub
This would negate the need for the user to manually insert their name (assuming their system username would suffice*) and also negate the need to unprotect the worksheet each time as I've used the UserInterfaceOnly option.
* Environment variables such as %USERNAME% can be falsified if a user wishes to do so and knows how - however someone typing their name into a textbox is even easier to falsify...

Mandatory fields red. Now how to save?

What it does: Requires fields from users. Blocks user from saving if specific fields are missing. Turns those fields red until saved correctly.
What I need: Well, how the hell am I supposed to save this...
What I would like: Since the worksheet is blank. I cannot save. and required fields are red. EVEN if I could save I would LIKE the cells to be on no fill until I roll it out.
View Original Post Here
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim xlSht As Worksheet
Dim cellsNotPopulated As Boolean
cellsNotPopulated = False
Set xlSht = ThisWorkbook.Worksheets("1st Call")
With xlSht
If .Range("F7") = "" Then
.Range("F7").Interior.Color = RGB(255, 0, 0)
cellsNotPopulated = True
Else
.Range("F7").Interior.ColorIndex = xlNone
End If
End With
If cellsNotPopulated = True Then
MsgBox "Please review the highlighted cells and ensure the fields are populated."
Cancel = True
End If
End Sub
If you are in the middle of development and want to "break the rules" and save your current efforts, then in a standard module:
Sub MyPrivateSave()
Application.EnableEvents = False
ThisWorkbook.Save
Application.EnableEvents = True
End Sub
Of course, when you finish development, you would remove this little "save tool" before you send the workbook out to the users.
or add as the first line if environ("Username")=your username then exit sub

Excel Add-in with some info stored

I have created a UserForm1 in Excel and saved it as an add-in. This add-in works fine but it does not store some data that I need (does not store it in itself not in the opened excel). I have to store some information in cells A1 and A2 (in A1 Username, in A2 today's date).
When I run this add-in the UserForm1 does not contain these values.
Is there a way how I can store the UserName and get the updated date?
Here is the code for UserForm1:
Private Sub UserForm1_Initialize()
Me.DocumentName.Text = ActiveWorkbook.FullName
DocumentName.Visible = False
TextBoxDate.Value = Worksheets("Sheet1").Cells(2, "A").Value
TextBoxDate.Value = CDate(TextBoxDate.Value)
UserName.Visible = False
Userform1.UserName.Text = CStr(Range("A1").Value)
'If A1 is empty pops up a UserRegister form
If UserName = "" Then
UserRegister.Show
End If
End Sub
UserRegister form code:
Private Sub UserName_Change()
Sheets("Sheet1").Range("A1") = UserName.Text
End Sub
' I want to store the UserName, so the user does not have to enter it every single time
Private Sub CommandButtonGO_Click()
ThisWorkbook.Save
Unload Me
End Sub
To get the date I just use the formula =TODAY() in Cell A2. I know there are other ways, but I found this one very simple.
Can you try this?
UserForm UserForm1:
Private Sub UserForm1_Initialize()
Me.DocumentName.Text = ActiveWorkbook.FullName
DocumentName.Visible = False
TextBoxDate.Value = ThisWorkbook.Worksheets("Sheet1").Range("A2").Value
'TextBoxDate.Value = CDate(TextBoxDate.Value)
UserName.Visible = False
UserForm1.UserName.Text = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
'If A1 is empty pops up a UserRegister form
If Len(UserName.Text) = 0 Then
UserRegister.Show
End If
Debug.Print "Name: " & ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
Debug.Print "Date: " & ThisWorkbook.Worksheets("Sheet1").Range("A2").Value
End Sub
UserForm UserRegister:
Private Sub UserName_Change()
CommandButtonGO.Enabled = Not (UserName.Text = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value)
End Sub
' I want to store the UserName, so the user does not have to enter it every single time
Private Sub CommandButtonGO_Click()
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Trim(UserName.Text)
ThisWorkbook.Worksheets("Sheet1").Range("A2").Value = Now
ThisWorkbook.Save
Unload Me
End Sub
Private Sub UserRegister_Initialize()
UserName.Text = UCase(Environ("USERNAME"))
End Sub
Well, I figured out how I can do it.
To get a user name i used a code from here : Getting computer name using VBA (It also says how to get User Name there)
To get current date of entry I just changed the code for output to:
ActiveCell.Offset(1, 0).Select 'Date column A
ActiveCell.Value = Date
And it outputs the current date in my LOGfile excel.
Thanks a lot for your help =)