I've created a button, then assigned a macro to it which is in module1. when I select a cell within a range, then press the button, I want that cell to be given a value. if a cell within the range is not selected then pressing the button should pop up with a message box. I am just starting to write the code and already getting an issue.
If Intersect(Target, Range("D12:AS23")) Is Nothing Then
MsgBox "Please select a date.", , "Error"
Exit Sub
Else
Edit: I've got past this issue now using active cell instead of the target. but now I'm struggling again at the next bit. its saying application/object-defined error and highlighting this line. full code below
Cells(LastRow, 2).Value = Application.SumIf(Sheets("Settings").range("ListEmployeeNames"), Cells(3, 2).Value, Sheets("Settings").range("ListEmployeeID"))
Sub AddNote()
Dim SelectedDate As Date
SelectedDate = Cells(ActiveCell.Row, 2) - 1 + ActiveCell.Value
If intersect(ActiveCell, range("D12:AS23")) Is Nothing Then
MsgBox "Please select a date.", , "Error"
Exit Sub
Else
With Sheets("Notes")
xtt = Application.InputBox("Insert your Comment here", "Comment")
If xtt = vbNullString Or xtt = False Then
End If
Dim LastRow As Integer
LastRow = 2 + .listobjects("TblNotes").range.rows.Count
Cells(LastRow, 2).Value = Application.SumIf(Sheets("Settings").range("ListEmployeeNames"), Cells(3, 2).Value, Sheets("Settings").range("ListEmployeeID"))
Cells(LastRow, 4).Value = SelectedDate
Cells(LastRow, 5).Value = xht
End With
End If
End Sub
Got it working 90% on my own, thanks to #LeeLiFong for tipping me off about "target" being an issue and also #BraX for point int he right direction about including arguements to qualify things. I cant accept my answer for another 48 hours.
Dim SelectedDate As Date
SelectedDate = Cells(ActiveCell.Row, 2) - 1 + ActiveCell.Value
If intersect(ActiveCell, range("D12:AS23")) Is Nothing Then
MsgBox "Please select a date.", , "Error"
Exit Sub
Else
Call SmoothCodeStart
With Sheets("Notes")
xt4 = Application.InputBox("Insert your Comment here", "Comment")
If xt4 = vbNullString Or xt4 = False Then
End If
Dim LastRow As Integer
LastRow = 2 + .listobjects("TblNotes").range.rows.Count
.Cells(LastRow, 2).Value = Application.SumIf(Sheets("Settings").range("ListEmployeeNames"), Cells(3, 2).Value, Sheets("Settings").range("ListEmployeeID"))
.Cells(LastRow, 4).Value = SelectedDate
.Cells(LastRow, 6).Value = xt4
End With
Call SmoothCodeEnd
End If
One of our spreadsheets requires a userform. When trying to paste the user's values to the sheet housing the data, I get error code 13: type mismatch.
All the fields are textboxes. One line of code identical except the address of where we're posting the information works.
Here's what I have:
Public Sub btnSubmit_Click()
Dim TableSht As Worksheet
Dim NextRow As Long
Set TableSht = ThisWorkbook.Sheets("Table")
TableSht.Visible = True
'https://www.mrexcel.com/forum/excel-questions/1017033-making-all-fields-userform-mandatory.html#post4880848
'determine if any fields were left blank
For Each Control In Me.Controls '
Select Case TypeName(Control)
Case "TextBox"
If Control.Value = vbNullString Then
MsgBox "empty field in " & Control.Name
Exit For
End If
Case Else
End Select
Next Control
'data is housed in E3:J3, E5:J5, E7:J7, E9:J9. if statement determines what row information
'should be entered on.
If TableSht.Range("E3") = "" Then
NextRow = 3
ElseIf TableSht.Range("E5") = "" Then
NextRow = 5
ElseIf TableSht.Range("E7") = "" Then
NextRow = 7
ElseIf TableSht.Range("E9") = "" Then
NextRow = 9
Else
MsgBox ("There are no more available rows. Contact Craig for additional assistance.")
End If
'paste the user's data entry into the appropriate cells
With TableSht
.Cells(NextRow, 5) = Me.tbOwner
.Cells(NextRow, 6) = CDate(Me.tbDate)
.Cells(NextRow, 7) = Me.tbChange
'Me.tbChange.Value = CDec(Me.tbChange) 'no longer use this but one of my attempts
.Cells(NextRow, 8) = Me.tbAmount
.Cells(NextRow, 9) = Me.tbOriginal
.Cells(NextRow, 10) = Me.tbReason
.Cells(NextRow, 7).Value = Format(Range("G" & NextRow) / 100, "0.00%")
.Cells(NextRow, 8).Value = Format(Range("H" & NextRow), "$##.##")
.Cells(NextRow, 9).Value = Format(Range("I" & NextRow) / 100, "0.00%")
End With
Sheets("Rate Calculator v8").Select
TableSht.Visible = xlVeryHidden
Unload Me
End
End Sub
The error occurs on
.Cells(NextRow, 7).Value = Format(Range("G" & NextRow) / 100, "0.00%")
There's no error if I remove the line and cycle through the two after it, even though the last line before "end with" is essentially the same statement.
I've tried swapping the two lines of code that are similar. "Cells(NextRow, 7)..." and ".Cells(NextRow, 9)..." but the error still shows up on the "Cells(NextRow, 7)..." line.
I've confirmed the cells the data is pasted in columns G and I are both formatted as "percentage".
Qualify your Range usage with a sheet. If the sheet is also TableSht, the below should work. If the Range is from a different sheet, qualify that sheet
= Format(.Range("G" & NextRow) / 100, "0.00%")
= Format(.Range("H" & NextRow), "$##.##")
= Format(.Range("I" & NextRow) / 100, "0.00%")
I recently started learning how to use VBA since I suddenly got put into a position where I need to know it. I've been doing research on coding and such but I feel like I'm messing up every step of the way. I was asked to create a userform where people could enter their time, date, production, task, and a comment box. I was also asked to have both the input sheet and the data sheet locked, on top of that my boss wanted the sheet itself to save when closed so when workers entered their information they wouldn't save.
Private Sub cmdAdd_Click()
Dim lRow As Long
Dim lPart As Long
Dim ws As Worksheet
Set ws = Worksheets("Data")
'find first empty row in database
lRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'check for a part number
If Trim(Me.txtComment.Value) = "" Then
Me.txtComment.SetFocus
MsgBox "Comment is required"
End If
'check for a part number
If Trim(Me.ComboBox1.Value) = "" Then
Me.ComboBox1.SetFocus
MsgBox "Date is required!"
End If
'check for a part number
If Trim(Me.txtTime.Value) = "" Then
Me.txtTime.SetFocus
MsgBox "Time is required"
End If
'check for a part number
If Trim(Me.cboProject.Value) = "" Then
Me.cboProject.SetFocus
MsgBox "Project is required"
End If
'check for a part number
If Trim(Me.cboTask.Value) = "" Then
Me.cboTask.SetFocus
MsgBox "Task is required"
Exit Sub
End If
'copy the data to the database
'use protect and unprotect lines,
' with your password
' if worksheet is protected
With ws
' .Unprotect Password:="password"
.Cells(lRow, 1).Value = Me.ComboBox1.Value
.Cells(lRow, 2).Value = Me.txtTime.Value
.Cells(lRow, 3).Value = Me.txtCount.Value
.Cells(lRow, 4).Value = Me.cboUser.Value
.Cells(lRow, 5).Value = Me.cboProject.Value
.Cells(lRow, 6).Value = Me.cboTask.Value
.Cells(lRow, 7).Value = Me.txtComment.Value
' .Protect Password:="password"
'clear the data
Me.cboUser.Value = ""
Me.ComboBox1.Value = ""
Me.txtTime.Value = ""
Me.txtCount.Value = ""
Me.cboProject.Value = ""
Me.cboTask.Value = ""
Me.txtComment.Value = ""
Me.ComboBox1.Value = Format(Date, "Short Date")
MsgBox ("Work Submitted, proceed to close the form and save the workbook.")
End With
End Sub
Apologies in advance for how awful the code probably is, but it seemed to work just enough for what I was going, the only problem was that when I was recently testing it even if I had a message saying comment required or task required it would still paste information into the datasheet which I don't want to happen.
In Excel VBA, I am running into an "error" that halts the macro and a message displays "Code execution has been interrupted." I wrote error in quotations because when I selected debug and examined the line of code that prompted the error, I saw that it was logically sound.
I originally ran into the error at On Error GoTo 0. When I comment out a block around the error, then I get a new line that produces the same error. And, again, when I examine it in debug mode the new "error" is logically sound. Here is the exact line:
If rRange.Row <> 3 And rRange.Row <> 17 Then
FYI, rRange.Row = 3 in this case, so it shouldn't produce an error.
Why is this happening and how can I fix it?
UPDATE Code now produces the error on the End Sub line.
Here is the section that fails:
Sub Review()
Dim WorkRange As Range
Dim FoundCells As Range
Dim Cell As Range
Dim a As String
Dim policy As String
Dim rRange As Range
Set RR = Sheets("Ready for Review")
Set OG = ActiveSheet
OG.Unprotect ("Password")
RR.Activate
On Error Resume Next
Application.DisplayAlerts = False
Set rRange = Application.InputBox(Prompt:= _
"Please select POLICY to review.", _
Title:="SPECIFY POLICY", Type:=8)
On Error GoTo 0
Application.DisplayAlerts = True
If rRange.Row <> 3 And rRange.Row <> 17 Then
MsgBox "Value other than a POLICY was selected. Select the cell that contains the correct policy number."
Exit Sub
Else
policy = rRange.Value
End If
Application.ScreenUpdating = False
OG.Cells(12, 2).Locked = False
Set WorkRange = OG.UsedRange
For Each Cell In WorkRange
If Cell.Locked = False Then
col1 = Cell.Column
Row = Cell.Row
a = OG.Cells(Row, 1)
If Not a = "" Then
row2 = Application.WorksheetFunction.Match(a, RR.Range("A:A"), 0)
Cell.Value = RR.Cells(row2, rRange.Column + col1 - 2)
End If
End If
Next Cell
OG.Unprotect ("Password")
OG.Cells(33, 3).Locked = False
If (Right(OG.Cells(5, 2), 2) = "UL" Or Right(OG.Cells(5, 2), 2) = "IL" Or Right(OG.Cells(5, 2), 2) = "PL") Then
With OG.Cells(33, 3)
.Value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""Total*"",A:A,0)))-SUM(C34:C37)"
.Locked = True
End With
ElseIf Right(OG.Cells(5, 2), 2) = "WL" Then
With OG.Cells(33, 3)
.Value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0))) - IFERROR(INDEX(C34:C37,MATCH(""Additional"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Paid"",B34:B37,0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Additional Agreement - SPPUA"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Flexible Agreement - FLXT10/20"",B34:B37, 0)),0)"
.Locked = True
End With
Else
With OG.Cells(33, 3)
.Value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0)))"
.Locked = True
End With
End If
OG.Activate
Cells(Application.WorksheetFunction.Match("Last Month Paid ($)", Range("A:A"), 0), 2).NumberFormat = "$#,##0.00;[Red]$#,##0.00"
OG.Protect ("Password")
Application.ScreenUpdating = True
End Sub
Oh, that brings back memories for me. I think I used to get this error about 10 years ago Excel 2003? Maybe?. Excel would get itself into a bit of a state. Nothing was wrong with the code, just it would keep coming back with that error.
If you save your work close Excel and then reopen, does the error go away?
If I remember right, it was caused when I called some external API. Maybe some other API call in your is causing this error but manifesting at this point... perhaps.
Sorry but it was 10+ years ago :)
even if you went through it, you may want to consider the following "restyling" of the code you posted
Option Explicit
Sub Review()
Dim Cell As Range, rRange As Range
Dim a As String
Dim RR As Worksheet, OG As Worksheet
Set RR = Sheets("Ready for Review")
Set OG = ActiveSheet
OG.Unprotect ("Password")
Set rRange = GetUserInpt(RR)
If rRange Is Nothing Then
MsgBox "You aborted the POLICY selection" _
& vbCrLf & vbCrLf _
& "the procedure ends" _
, vbInformation
Exit Sub
End If
Application.ScreenUpdating = False
OG.Cells(12, 2).Locked = False
For Each Cell In OG.UsedRange
With Cell
If Not .Locked Then
a = OG.Cells(.row, 1)
If Not a = "" Then .value = RR.Cells(CLng(Application.WorksheetFunction.Match(a, RR.Range("A:A"), 0)), _
rRange.Column + .Column - 2)
End If
End With
Next Cell
With OG.Cells(33, 3)
.Locked = False
Select Case Right(OG.Cells(5, 2), 2)
Case "UL", "IL", "PL"
.Formula = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""Total*"",A:A,0)))-SUM(C34:C37)"
Case "WL"
.Formula = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0))) - IFERROR(INDEX(C34:C37,MATCH(""Additional"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Paid"",B34:B37,0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Additional Agreement - SPPUA"",B34:B37, 0)),0) - IFERROR(INDEX(C34:C37,MATCH(""Flexible Agreement - FLXT10/20"",B34:B37, 0)),0)"
Case Else
.value = "=IF(INDEX(B:B,MATCH(""Total*"",A:A,0))="""",0,INDEX(B:B,MATCH(""*"",A:A,0)))"
End Select
.Locked = True
End With
OG.Activate
Cells(Application.WorksheetFunction.Match("Last Month Paid ($)", Range("A:A"), 0), 2).NumberFormat = "$#,##0.00;[Red]$#,##0.00"
OG.Protect ("Password")
Application.ScreenUpdating = True
End Sub
Function GetUserInpt(sht As Worksheet) As Range
Dim rRange As Range
Application.DisplayAlerts = False
sht.Activate
On Error GoTo InputBoxCanceled
Do While rRange Is Nothing
Set rRange = Application.InputBox(Prompt:="Please select POLICY to review.", _
Title:="SPECIFY POLICY", _
Default:=sht.Cells(3, 1).Address, _
Type:=8)
If rRange.Parent.Name <> sht.Name Then
MsgBox "You must select a cell in '" & sht.Name & "' sheet"
sht.Activate
Set rRange = Nothing
Else
If rRange.row <> 3 And rRange.row <> 17 Then
MsgBox "Value other than a POLICY was selected" _
& vbCrLf & vbCrLf _
& "Select the cell that contains the correct policy number" _
, vbCritical
Set rRange = Nothing
End If
End If
Loop
Set GetUserInpt = rRange
InputBoxCanceled:
On Error GoTo 0
Application.DisplayAlerts = True
End Function
the main revision applies to:
added a GetUserInpt function to handle the policy selection
this function:
checks for both the correct selection row and sheet, too (since it's possible the user shifts to another worksheet during selection!)
runs a loop until the user selects a proper cell
exits selection upon user canceling the InputBox, as the only loop escape possibility
made some simplifications here and there, like:
eliminated Activate statements unless really needed
reduced the amount of variables to only (nearly) strictly needed ones
added some With ... End With blocks to add readability
used a Select Case block instead of an If ... Then ... Else if ... Else ... End if one, for readability again
changed .Value to .Formula, for a proper syntax
all what above could help you with this project and in future ones, too
I type three entries in specific cells
[A2,B2,C2] and run code to take this data to the first empty row in a table.
The code also prevents duplicates based on the entered value in cell B2. If it already exists in the range (B2:B5000) it prevent duplicates.
The problem is it does not ignore the case.
For example:
I enter value "Acetic Acid"
After awhile I add "acetic Acid" or change any letter case.
The code adds it normally without preventing.
How do I ignore the letter case?
Sub tarheel()
LastRow = Range("A10000").End(xlUp).Row + 1
LR = Range("b10000").End(xlUp).Row + 1
For r = 5 To LR
If Cells(r, 2) = Range("b2") Then MsgBox "This Item Name already exist, No shift will done": Exit Sub
Next
Cells(LastRow, 1).Value = Range("A2").Value
Cells(LastRow, 2).Value = Range("B2").Value
Cells(LastRow, 3).Value = Range("C2").Value
Range("A2:C2").Select
Selection.ClearContents
Range("A2").Select
End Sub
thanks for all your replies and i will try it too and give feedback to you.
i could figure it out by adding this line at the top of my module.
Option Compare Text
and it fixed my problem.
thanks
To change case in VBA, you have LCase and UCase, which will respectively change all of your string into lower case or upper case.
Here is your code with the change and got ride of the useless (and ressource-greedy) select at the end :
Sub tarheel()
LastRow = Range("A10000").End(xlUp).Row + 1
LR = Range("b10000").End(xlUp).Row + 1
IsIn = False
For r = 5 To LR
If LCase(Cells(r, 2)) = LCase(Range("b2")) Then _
MsgBox "This Item Name already exist, No shift will done": Exit Sub
Next
Cells(LastRow, 1).Value = Range("A2").Value
Cells(LastRow, 2).Value = Range("B2").Value
Cells(LastRow, 3).Value = Range("C2").Value
Range("A2:C2").ClearContents
'Range("A2").Select
End Sub
You can replace your loop that compares for existing values with a case insensitive one by forcing both values to either upper or lower case.
For r = 5 To LR
If lcase(Cells(r, 2)) = lcase(Range("b2")) Then
MsgBox "This Item Name already exist, No shift will done"
Exit Sub
end if
Next
It may be more efficient to use a case-insensitive worksheet function to check the whole range at once.
If cbool(application.countif(Range("B5:B" & LR), Cells(r, 2))) Then
MsgBox "This Item Name already exist, No shift will done"
Exit Sub
end if
Another possible:
If not iserror(application.match(Cells(r, 2), Range("B5:B" & LR), 0)) Then
MsgBox "This Item Name already exist, No shift will done"
Exit Sub
end if
Sub tarheel()
LastRow = Range("A10000").End(xlUp).Row + 1
LR = Range("b10000").End(xlUp).Row + 1
IsIn = False
For r = 5 To LR
If LCase(Cells(r, 2)) = LCase(Range("b2")) Then _
MsgBox "This Item Name already exist, No shift will done": Exit Sub
Next
Cells(LastRow, 1).Value = Range("A2").Value
Cells(LastRow, 2).Value = Range("B2").Value
Cells(LastRow, 3).Value = Range("C2").Value
Range("A2:C2").ClearContents
'Range("A2").Select
End Sub