I need a macro that prevent the excel from closing while I fill in number remotely to a column. Initially I already ask the user to enter the ID. the next step is prevent closing . How can it be done?
below is the code for ID enter and cell selection.
Sub Enter_1()
Dim data_1 As String
Dim sCell As Variant
Dim rslt As Integer
Dim x As Integer
Do
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
data_1 = InputBox(Prompt:="Enter Employee No.", Title:="Employee", Default:="Enter Employee No. here")
If data_1 = "" Then
QuestionToMessageBox = "Exit?"
YesOrNoAnswerToMessageBox = MsgBox(QuestionToMessageBox, vbYesNo, "No")
End If
If YesOrNoAnswerToMessageBox = vbNo Then
data_1 = InputBox(Prompt:="Enter Employee No.", Title:="Employee", Default:="Enter Employee No. here")
Exit sub
End If
If Not IsNumeric(data_1) Or data_1 = "" Then
rslt = 0
Else: rslt = 1
End If
If rslt = 0 Then
MsgBox "You can only enter a number in this field"
Else:
Sheets("Oven After Assay Test").Activate
For x = 6 To 50
If Cells(x, 8).Value = "" Then
Cells(x, 8).Select
cancel = True
Exit For
End If
Next
End If
Loop While rslt = 0
End Sub
You can implement the requested functionality as follows:
Insert the code Module and add the following line:
Public FlagToClose As Boolean
In ThisWorkbook VBA code module add Sub:
Private Sub Workbook_Open()
FlagToClose = True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not FlagToClose Then Cancel = True
End Sub
Modify your procedure as followoing:
Sub Enter_1()
FlagToClose = False
'YOUR PROCEDURE
'.....................
FlagToClose = True
End Sub
Related
I have some code below that creates an input box, and I don't want to allow people to type symbols in. Is there something I can do to have a msgBox popup when someone enters a symbol that says not to, or disallow them altogether? Code pasted below. Thanks for any help up front :)
If AnswerYes = vbYes Then
Dim Discount1 As Variant
Discount1 = Application.InputBox("DO NOT ENTER % SIGN", "Product Discount Percentage", "##", Type:=1)
Dim Discount2 As Variant
Discount2 = Application.InputBox("DO NOT ENTER % SIGN", "SNS Discount net Percentage", "##", Type:=1)
This should work. The False response is for cancel. It will reject any text that isn't numeric. If you wanted something more sophisticated consider using ascii code.
Sub makeInput()
makeEntry:
theResponse = Application.InputBox("DO NOT ENTER % SIGN", "Product Discount Percentage", "##", Type:=1)
If theResponse = False Then Exit Sub
Dim i As Long
For i = 1 To Len(theResponse)
If Not (IsNumeric(Mid(theResponse, i, 1))) Then
MsgBox "Invalid Entry"
GoTo makeEntry
End If
Next i
End Sub
Create a userform like this
And then paste this code in the userform code area. The TextBox1_KeyPress will ensure the user doesn't type anything other than numbers and decimal.
Option Explicit
Private Sub UserForm_Initialize()
MyValue = 0: Cancelled = False
End Sub
'~~> OK Button
Private Sub CommandButton1_Click()
If Len(Trim(TextBox1.Text)) = 0 Then
MsgBox Label1.Caption
Exit Sub
End If
MyValue = Val(TextBox1.Text)
Unload Me
End Sub
'~~> CANCEL Button
Private Sub CommandButton2_Click()
Unload Me
Cancelled = True
End Sub
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case vbKey0 To vbKey9, vbKeyBack, vbKeyClear, vbKeyDelete, vbKeyLeft, vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
If KeyAscii = 46 Then If InStr(1, TextBox1.Text, ".") Then KeyAscii = 0
Case Else
KeyAscii = 0
Beep
End Select
End Sub
Now you can use it like this. Paste this code in a module
Option Explicit
Public MyValue As Double
Public Cancelled As Boolean
Sub Sample()
Dim frm As New UserForm1
Dim Discount1 As Double
Dim Discount2 As Double
With frm
.Caption = "WhatEver Title"
.Label1.Caption = "Enter Product Discount Percentage"
.Show
End With
If Cancelled = False Then
Discount1 = MyValue
MsgBox Discount1
End If
Set frm = New UserForm1
With frm
.Caption = "WhatEver Title"
.Label1.Caption = "Enter SNS Discount net Percentage"
.Show
End With
If Cancelled = False Then
Discount2 = MyValue
MsgBox Discount2
End If
End Sub
EDIT
If you want, you can create a common function for the module code.
Option Explicit
Public MyValue As Double
Public Cancelled As Boolean
Sub Sample()
Dim Discount1 As Double
Dim Discount2 As Double
Discount1 = ShowInputBox("WhatEver Title", "Enter Product Discount Percentage")
If Cancelled = False Then MsgBox Discount1
Discount2 = ShowInputBox("WhatEver Title", "Enter SNS Discount net Percentage")
If Cancelled = False Then MsgBox Discount2
End Sub
Private Function ShowInputBox(Title As String, Msg As String) As Double
Dim frm As New UserForm1
With frm
.Caption = Title
.Label1.Caption = Msg
.Show
End With
If Cancelled = False Then ShowInputBox = MyValue
End Function
enter image description hereI have a spreadsheet that has 3 checkbox options for each row, I have created a VBA to disable the other 2 checkboxes once a checkbox is created (so that only 1 checkbox can be checked), however my solution only works for one row and I need some help in rewriting this so that it will apply to all rows please. (I'm new to VBA).
The code I have used is this:
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
CheckBox2.Value = False
CheckBox2.Enabled = False
CheckBox3.Value = False
CheckBox3.Enabled = False
Else
CheckBox2.Value = False
CheckBox2.Enabled = True
CheckBox3.Value = False
CheckBox3.Enabled = True
End If
End Sub
Private Sub CheckBox2_Click()
If CheckBox2.Value = True Then
CheckBox1.Value = False
CheckBox1.Enabled = False
CheckBox3.Value = False
CheckBox3.Enabled = False
Else
CheckBox1.Value = False
CheckBox1.Enabled = True
CheckBox3.Value = False
CheckBox3.Enabled = True
End If
End Sub
Private Sub CheckBox3_Click()
If CheckBox3.Value = True Then
CheckBox1.Value = False
CheckBox1.Enabled = False
CheckBox2.Value = False
CheckBox2.Enabled = False
Else
CheckBox1.Value = False
CheckBox1.Enabled = True
CheckBox2.Value = False
CheckBox2.Enabled = True
End If
End Sub
You should probably just use Radios it would be a lot simpler.
If you are intent on doing this you will need to delete all your boxes and then put this code in. It will create and name your boxes and assign them code on click.
Alright, This needs to go in your Sheet module:
Sub Worksheet_Activate()
'Change Module2 to whatever the module name you are using is.
Module2.ActivateCheckBoxes ActiveSheet
End Sub
This next stuff will go into the module you're referencing from the Worksheet Module.
Sub ActivateCheckBoxes(sht As Worksheet)
If sht.CheckBoxes.Count = 0 Then
CreateCheckBoxes sht
End If
Dim cb As CheckBox
For Each cb In sht.CheckBoxes
'You may be able to pass sht as an object, It was giving me grief though
cb.OnAction = "'Module2.CheckBoxClick """ & cb.name & """, """ & sht.name & """'"
Next cb
End Sub
Sub CreateCheckBoxes(sht As Worksheet)
Dim cell As Range
Dim chkbox As CheckBox
With sht
Dim i As Long
Dim prevrow As Long
prevrow = 0
For Each cell In .Range("B2:D5") 'Change this to whatever range you want.
If prevrow < cell.row Then
prevrow = cell.row
i = 0
End If
Set chkbox = .CheckBoxes.Add(cell.Left, cell.Top, 30, 6)
With chkbox
.name = "CheckBox" & i & "_" & cell.row
.Caption = ""
End With
i = i + 1
Next cell
End With
End Sub
Sub CheckBoxClick(chkname As String, sht As String)
Dim cb As CheckBox
With Worksheets(sht)
For Each cb In .CheckBoxes
If Split(cb.name, "_")(1) Like Split(chkname, "_")(1) And Not cb.name Like chkname Then
cb.Value = -4146
End If
Next cb
End With
End Sub
You do not say anything about your sheet check boxes type... Please, test the next solution. It will be able to deal with both sheet check boxes type:
Copy this two Subs in a standard module:
Public Sub CheckUnCheckRow(Optional strName As String)
Dim sh As Worksheet, s As CheckBox, chK As OLEObject ' MSForms.CheckBox
Set sh = ActiveSheet
If strName <> "" Then
Set chK = sh.OLEObjects(strName) '.OLEFormat.Object
solveCheckRow chK.Object.Value, sh, Nothing, chK
Else
Set s = sh.CheckBoxes(Application.Caller)
solveCheckRow s.Value, sh, s
End If
End Sub
Sub solveCheckRow(boolVal As Long, sh As Worksheet, chF As CheckBox, Optional chK As OLEObject)
Dim s As CheckBox, oObj As OLEObject, iCount As Long
If Not chF Is Nothing Then
For Each s In sh.CheckBoxes
If chF.TopLeftCell.Address <> s.TopLeftCell.Address Then
If s.TopLeftCell.Row = chF.TopLeftCell.Row Then
s.Value = IIf(boolVal = -4146, 1, -4146): iCount = iCount + 1
If iCount = 2 Then Exit Sub
End If
End If
Next
ElseIf Not chK Is Nothing Then
For Each oObj In sh.OLEObjects
If oObj.TopLeftCell.Address <> chK.TopLeftCell.Address Then
If oObj.TopLeftCell.Row = chK.TopLeftCell.Row Then
boolStopEvents = True
oObj.Object.Value = IIf(boolVal = 0, True, False): iCount = iCount + 1
boolStopEvents = False
If iCount = 2 Then Exit Sub
End If
End If
Next
End If
End Sub
For case of Form check boxes type:
a). Manually assign the first sub to all your Form Type check boxes (right click - Assign Macro, choose CheckUnCheckRow and press OK).
b). Automatically assign the macro:
Dim sh As Worksheet, s As CheckBox
Set sh = ActiveSheet ' use here your sheet keeping the check boxes
For Each s In sh.CheckBoxes
s.OnAction = "'" & ThisWorkbook.Name & "'!CheckUnCheckRow"
Next
End Sub
If your check boxes have already assigned a macro, adapt CheckUnCheckRow, in Form check boxes section, to also call that macro...
For case of ActiveX check boxes:
a). Create a Public variable on top of a standard module (in the declarations area):
Public boolStopEvents
b). Manually adapt all your ActiveX check boxes Click or Change event, like in the next example:
Private Sub CheckBox1_Click()
If Not boolStopEvents Then CheckUnCheckRow "CheckBox1"
End Sub
Private Sub CheckBox2_Click()
If Not boolStopEvents Then CheckUnCheckRow "CheckBox2"
End Sub
Private Sub CheckBox3_Click()
If Not boolStopEvents Then CheckUnCheckRow "CheckBox3"
End Sub
and so on...
c). Or do all that with a click, using the next piece of code:
Sub createEventsAllActiveXCB()
Dim sh As Worksheet, oObj As OLEObject, strCode As String, ButName As String
Set sh = ActiveSheet 'use here your sheet keeping ActveX check boxes
For Each oObj In sh.OLEObjects
If TypeName(oObj.Object) = "CheckBox" Then
ButName = oObj.Name
strCode = "Private Sub " & ButName & "_Click()" & vbCrLf & _
" If Not boolStopEvents Then CheckUnCheckRow """ & ButName & """" & vbCrLf & _
"End Sub"
addClickEventsActiveXChkB sh, strCode
End If
Next
End Sub
Anyhow, the code cam be simplified in order to deal with only a type of such check boxes. If you intend to use it and looks too bushy, I can adapt it only for the type you like. Like it is, the code deals with both check box types, if both exist on the sheet...
Save the workbook and start playing with the check boxes. But, when you talk about check boxes on a row, all tree of them must have the same TopLeftCell.Row...
I have VBA code which is validating the data entered on user form with a static list of refernce data present in one of teh sheets on the excel .
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim i As Long, LastRow As Long
Dim iExit As VbMsgBoxResult
i = 0
LastRow = 0
LastRow = Worksheets("sheet1").Range("H1").CurrentRegion.Rows.Count
For i = 2 To LastRow
If Trim(Sheet1.Cells(i, 8)) = Trim(TextBox1.Text) Then
Exit For
End If
Next i
If Trim(Sheet1.Cells(i, 8)) <> Trim(TextBox1.Text) Then
iExit = MsgBox("Invalid Customer ShortName ,Confirm if you want to ignore", vbQuestion + vbYesNo, "Data Entry Form")
If iExit = vbYes Then
Cancel = False
Else
Cancel = True
End If
End If
End Sub
issue :
I keep on geting Subscript out of range error intermittently on this line :
LastRow = Worksheets("sheet1").Range("H1").CurrentRegion.Rows.Count
Some time the code works sometimes does not .
Employee Login System using Excel with Macro.
I'm using a very simple technique of "if elseif then"
I want to display Employee Name when their ID is typed.
I used very simple code:
Dim CM As Boolean
Dim UserRange As Range
Dim x As Range
'EASY
Private Sub cmdClear_Click()
txtEmpID.Value = ""
txtName.Value = ""
txtEmpID.SetFocus
End Sub
Private Sub cmdLogin_Click()
End Sub
Private Sub txtEmpID_Change()
'If txtEmpID.Value = "111" Then
'txtName.Value = "Ryan"
'
'ElseIf txtEmpID.Value = "222" Then
'txtName.Value = "Tim"
'
'End If
End Sub
Private Sub UserForm_activate()
Do
If CM = True Then Exit Sub
TextBox1 = Format(Now, "hh:mm:ss")
DoEvents
Loop
Set UserRange = Sheets("Sheet1").Range("B:B")
For Each x In UserRange.Cells
If x.Value = txtEmpID.Text Then
x.Offset(1, 0) = txtName.Value
End If
Exit For
Next x
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
CM = True
End Sub
However I want to have a sheet that holds Employee Name (column A) and ID(column B) Sheet
Then from there, I can add more employee names and IDs. Also when I click on Login it will display the current time in Column C and then It will also display their time-out. Here's my main form Main Form
Thank you so much.
Not 100% sure I understand but here's my response:
Here's a way to update the field from the worksheet:
Private Sub txtEmpID_Change()
Dim mySheet As Worksheet
Dim myRange As Range
Set mySheet = Sheets("Emp_ID")
Set myRange = mySheet.Range("B:B").Find(txtEmpID.Value, , , xlWhole)
If Not myRange Is Nothing Then
txtName.Value = myRange.Offset(0, -1)
Else
txtName.Value = "Match not found"
End If
End Sub
Set that to occur whenever there's an update.
As for recording the login time: myRange.offset(0,1) = Format(Now,"hh:mm:ss")
How will you know / display the logout time when someone is logging in?
I have code in this module:
Sub HideSalTable()
User = Worksheets("log").Range("R1").Value
If User = ThisWorkbook.Worksheets("SSSSSS").Range("za1").Value Then
Columns("S:AA").EntireColumn.Hidden = True
ElseIf User = ThisWorkbook.Worksheets("SSSSSS").Range("za3").Value Then
Columns("S:AA").EntireColumn.Hidden = False
ElseIf User = ThisWorkbook.Worksheets("SSSSSS").Range("za4").Value Then
Columns("S:AA").EntireColumn.Hidden = False
End If
End Sub
I have a button to redirect me to ThisWorkbook.Worksheets("SSSSSS") with this code:
Private Sub Change_SSSSSS_Button_Click()
Dim pass1 As String
Dim pass2 As String
pass1 = ThisWorkbook.Worksheets("SSSSSS").Range("za3").Value
pass2 = ThisWorkbook.Worksheets("SSSSSS").Range("za4").Value
Dim Inp
Dim lTries As Long
lTries = 1
Do
Inp = InputBoxDK("enter password", "Zmhnk")
If Inp = "" Or Inp = vbCancel Then Exit Sub '* Cancel button pressed or nothing entered
If Inp = (pass1) Or Inp = (pass2) Then
Exit Do
End If
lTries = lTries + 1
If lTries > 4 Then
MsgBox "Error", vbInformation, "Zmhnk"
Exit Sub
Else
If MsgBox("try again", vbYesNo, "error_Zmhnk") = vbNo Then Exit Sub
End If
Loop
Application.ScreenUpdating = False
Sheets("SSSSSS").Visible = True
Sheets("SSSSSS").Activate
Application.ScreenUpdating = True
End Sub
The problem is when the user presses the button with the 2nd code I face an error and I don't know why.
The error:
Unable to set the hidden property of the range class run time error '1003'
Two things
1) You have not fully qualified your range. I understand that you are getting redirected but this is much safer.
Columns("S:AA").EntireColumn.Hidden = True
Change it to
ThisWorkbook.Sheets("SSSSSS").Columns("S:AA").EntireColumn.Hidden = True
2) I believe your worksheet is protected. You have to unprotect it. You can do that as follows
ThisWorkbook.Sheets("SSSSSS").Unprotect "myPassword"
when you have the control from the Form there is no Problem
but if you have it from the worksheet itself then it works actually but with Error:1004
so just use ( On Error Resume Next)
Private Sub ComboBox1_Change()
Dim wsMon As Worksheet
Set wsMon = ThisWorkbook.Worksheets("Montag")
On Error Resume Next
Select Case ComboBox1.ListIndex
Case 0
xHide (False)
wsMon.Rows("12:25").EntireRow.Hidden = True
xHide (True)
Case 1
xHide (False)
wsMon.Rows("12:25").EntireRow.Hidden = False
wsMon.Rows("19:25").EntireRow.Hidden = True
xHide (True)
Case 2
xHide (False)
wsMon.Rows("12:25").EntireRow.Hidden = False
xHide (True)
End Select
End Sub
xHide is a Boolean Function :
true
Application.ScreenUpdating = True
Application.DisplayAlerts = True
or False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
I had a similar issue (only the error code was 1004, but the error message was the same). What solved the issue at my Excel sheet was to remove a comment which was within the range that I tried to hide. It seems like comments are not allowed within the range that should be hidden.