Generate random code - mixed number & alphabet - excel

I want to record user data using a userform.
In first textbox, I will insert user's name.
Second textbox is their ID.
In the third textbox I want to generate a 5 character ID/code (mixed number & alphabet) by clicking the 'Generate' button (but I have no idea what is the coding).
Once I click 'Add user', I would like the data to be populated in the Excel sheet. I would like to insert number 1, 2, 3... in Column A, today's date (when the user details added) in Column B. Followed by the data added in the Userform in Column C, D & E.
Here is what I want the data to look like:
Here is code I copied from the site.
Private Sub CommandButton2_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Database")
'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'check for a Name number
If Trim(Me.TextBox1.Value) = "" Then
Me.TextBox1.SetFocus
MsgBox "Please complete the form"
Exit Sub
End If
'copy the data to the database
ws.Cells(iRow, 1).Value = Me.TextBox1.Value
ws.Cells(iRow, 2).Value = Me.TextBox2.Value
ws.Cells(iRow, 3).Value = Me.TextBox3.Value
MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"
'clear the data
Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.TextBox3.Value = ""
Me.TextBox1.SetFocus
End Sub

This will generate a five character random string of numbers and letters. You could assign to your button and output to your form rather than a message box.
Sub x()
Dim vOut(1 To 5), i As Long, n As Long
Randomize
For i = 1 To 5
n = WorksheetFunction.RandBetween(1, 2)
If n = 1 Then
vOut(i) = WorksheetFunction.RandBetween(0, 9)
Else
vOut(i) = Chr(64 + WorksheetFunction.RandBetween(1, 26))
End If
Next i
MsgBox Join(vOut, "")
End Sub

Related

Simple Excel VBA takes ages

I have written a simple VBA script (code below) that should inspect every cell in a certain column. Here I want to do some string manipulation ( i wante to search for "." in the string and then take the right side, but because I could not get it to work I always take the 4 digit as a start). I then copy the manipulated string into another cell and later back. The code works, but for some reason, it takes ages to run on only 35 cells!
I´m still a kook on VBA and wanted to get input what could be the reason for it and what I could improve to get a faster runtime. Is it because I take all strings froms 4 up to 50 ?
Sub EditStatus()
Application.DisplayAlerts = False
ActiveSheet.Name = "Backend"
myNum = Application.InputBox("Please enter the row number until which you would like to update the status column (only for new entries)")
For i = 2 To myNum
Cells(i, 20).Value = Mid(Cells(i, 10), 4, 50)
Cells(i, 10).Value = Cells(i, 20).Value
Next i
Range("T1:T200").Clear
Application.DisplayAlerts = True
End Sub
Thanks
No need for a loop. You can enter the formula in the entire range in 1 go and then convert them to values before putting the values back in Col J
Replace
For i = 2 To myNum
Cells(i, 20).Value = Mid(Cells(i, 10), 4, 50)
Cells(i, 10).Value = Cells(i, 20).Value
Next i
With
With Range("T2:T" & myNum)
.Formula = "=MID(J2, 4, 50)"
.Value = .Value
Range("J2:J" & myNum).Value = .Value
End With
Alternatively, you can directly perform the same action in Col J without the helper column T. For example you can do all that in 1 line as explained HERE as well
Simply replace
For i = 2 To myNum
Cells(i, 20).Value = Mid(Cells(i, 10), 4, 50)
Cells(i, 10).Value = Cells(i, 20).Value
Next i
Range("T1:T200").Clear
with
Range("J2:J" & myNum).Value = Evaluate("Index(MID(" & "J2:J" & myNum & ", 4, 50),)")
Replace Values In-Place
Adjust the values in the constants section.
This solution overwrites the data and doesn't use a helper column, but you can test it with one indicated near the end of the code.
Solve the renaming (Backend) part as needed.
The Code
Option Explicit
Sub EditStatus()
' Define constants.
Const sPrompt As String = "Please enter the row number until which you " _
& "would like to update the status column (only for new entries)"
Const sTitle As String = "Enter Number"
Const wsName As String = "Backend"
Const First As Long = 2
Const cCol As Long = 10 ' J
Const Delim As String = "."
' Define workbook.
Dim wb As Workbook: Set wb = ThisWorkbook ' Workbook containing this code.
' Require input.
Dim Last As Variant
Last = Application.InputBox( _
Prompt:=sPrompt, Title:=sTitle, Default:=First, Type:=1)
' Validate input.
If VarType(Last) = vbBoolean Then
MsgBox "You cancelled."
Exit Sub
End If
If Last < First Then
MsgBox "Enter a number greater than " & First - 1 & "."
Exit Sub
End If
If Int(Last) <> Last Then
MsgBox "Enter a WHOLE number greater than " & First - 1 & "."
Exit Sub
End If
' Define column range.
Dim rg As Range
Set rg = wb.Worksheets(wsName).Cells(First, cCol).Resize(Last - First + 1)
' Write values from column range to array.
Dim Data As Variant
If rg.Rows.Count > 1 Then
Data = rg.Value
Else
ReDim Data(1 To 1, 1 To 1): Data = rg.Value
End If
' Declare additional variables
Dim cValue As Variant ' Current Value
Dim i As Long ' Current Row (Array Row Counter)
Dim fPos As Long ' Current Delimiter Position
' Replace strings containing the delimiter, with the sub string
' to the right of it.
For i = 1 To UBound(Data)
cValue = Data(i, 1)
If Not IsError(cValue) Then
fPos = InStr(1, cValue, Delim)
If fPos > 0 Then
Data(i, 1) = Right(cValue, Len(cValue) - fPos)
End If
End If
Next i
' Maybe rather test with the following (writes to column 20 ("T")).
'rg.Offset(, 10).Value = Data
' Write values from array to column range.
rg.Value = Data
End Sub

How to modify a record in selected excel data sheet using VBA when there are multiple data sheets

I have a data entry form and multiple data sheets named as Table1 and Table2.I want to modify data in a particular row in the selected datasheet using data entry form. In the data entry form, there are two buttons called SAVE and MODIFY buttons. First there is a option to select a table that I want to save data. Then I click modify button and it asks us to enter the serial number to make the modification. When I enter serial no of particular row in selected data sheet, all the details of that particular row should be appeared on the data entry form to modify and save it to the same row using SAVE button. But it gives a error mentioning that "no record found" and it cannot detect the selection of datasheets. The VBA code that I have used for MODIFY button is given below. Please help me solve this problem sir.
Sub ModifyRecord()
Dim shTable As Worksheet
Dim shForm As Worksheet
Dim iCurrentRow As Integer
Dim sTableName As String
Set shForm = ThisWorkbook.Sheets("Form")
sTableName = shForm.Range("H7").Value
Set shTable = ThisWorkbook.Sheets(sTableName)
Dim irow As Long
Dim iSerial As Long
iSerial = Application.InputBox("Please enter Serial Number to make
modification.", "Modify", , , , , , 1)
On Error Resume Next
irow = Application.WorksheetFunction.IfError _
(Application.WorksheetFunction.Match(iSerial,
Sheets("sTableName").Range("A:A"), 0), 0)
On Error GoTo 0
If irow = 0 Then
MsgBox "No record found.", vbOKOnly + vbCritical, "No Record"
Exit Sub
End If
Sheets("Form").Range("L1").Value = irow
Sheets("Form").Range("M1").Value = iSerial
Sheets("Form").Range("H9").Value = Sheets("sTableName").Cells(irow, _
2).Value
Sheets("Form").Range("H11").Value = Sheets("sTableName").Cells(irow, _
3).Value
Sheets("Form").Range("H13").Value = Sheets("sTableName").Cells(irow, _
4).Value
Sheets("Form").Range("H15").Value = Sheets("sTableName").Cells(irow, _
5).Value
Sheets("Form").Range("H17").Value = Sheets("sTableName").Cells(irow, _
6).Value
Sheets("Form").Range("H19").Value = Sheets("sTableName").Cells(irow, _
7).Value
Sheets("Form").Range("H21").Value = Sheets("sTableName").Cells(irow, _
8).Value
Sheets("Form").Range("H23").Value = Sheets("sTableName").Cells(irow, _
9).Value
End Sub

How to update a record in selected excel data sheet using VBA when there are multiple data sheets

I have a data entry form and multiple data sheets named as Table1 and Table2.I want to modify data in a particular row in the selected datasheet using data entry form. In the data entry form, there are two buttons called SAVE and MODIFY buttons. First there is a option to select a table that I want to save data. Then I click modify button and it asks us to enter the serial number to make the modification. When I enter serial no of particular row in selected data sheet, all the details of that particular row should be appeared on the data entry form to modify and save it to the same row using SAVE button. But it gives a error mentioning that "no record found" and it can not detect the selection of datasheets. The VBA code that I have used for MODIFY button is given below. Please help me solve this problem sir.
Sub ModifyRecord()
Dim shTable As Worksheet
Dim shForm As Worksheet
Dim iCurrentRow As Integer
Dim sTableName As String
Set shForm = ThisWorkbook.Sheets("Form")
sTableName = shForm.Range("H7").Value
Set shTable = ThisWorkbook.Sheets(sTableName)
Dim irow As Long
Dim iSerial As Long
iSerial = Application.InputBox("Please enter Serial Number to make
modification.", "Modify", , , , , , 1)
On Error Resume Next
irow = Application.WorksheetFunction.IfError _
(Application.WorksheetFunction.Match(iSerial,
Sheets("sTableName").Range("A:A"), 0), 0)
On Error GoTo 0
If irow = 0 Then
MsgBox "No record found.", vbOKOnly + vbCritical, "No Record"
Exit Sub
End If
Sheets("Form").Range("L1").Value = irow
Sheets("Form").Range("M1").Value = iSerial
Sheets("Form").Range("H9").Value = Sheets("sTableName").Cells(irow, _
2).Value
Sheets("Form").Range("H11").Value = Sheets("sTableName").Cells(irow, _
3).Value
Sheets("Form").Range("H13").Value = Sheets("sTableName").Cells(irow, _
4).Value
Sheets("Form").Range("H15").Value = Sheets("sTableName").Cells(irow, _
5).Value
Sheets("Form").Range("H17").Value = Sheets("sTableName").Cells(irow, _
6).Value
Sheets("Form").Range("H19").Value = Sheets("sTableName").Cells(irow, _
7).Value
Sheets("Form").Range("H21").Value = Sheets("sTableName").Cells(irow, _
8).Value
Sheets("Form").Range("H23").Value = Sheets("sTableName").Cells(irow, _
9).Value
End Sub

Code to update a cell in next column(s) when userform data matches an existing cell - excel vba userform

I have a userform with 2 textboxes and 1 ComboBox. I want the user to input a serial number in "SN_Textbox1" and the 2nd textbox "RMA_Textbox2" automatically fills in with the matching value (coded and works!)
After they select the disposition from ComboBox1 and clicks submit... I want to update column 7 in the same row of that matching serial number...
However, it is just adding a new row at the moment...
'this assigns data to Data Sheet matching serial numbers or adds new values
Private Sub SubmitButton_Click()
Dim serial_ID As String
serial_ID = UCase(Trim(SN_TextBox1.Text))
Worksheets("RMA Tracker").Activate
lastrow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
For i = 2 To lastrow
'this assigns data to disposition column to matching entries in serial number column
If UCase(Worksheets("Sheet1").Cells(i, 4).Text) = serial_ID Then
Worksheets("Sheet1").Cells(i, 7).Value = ComboBox1.Text
'Searches for matching RMA & SN 'this assigns data to Log Sheet, if the data is brand new
ElseIf Worksheets("Sheet1").Cells(i, 4).Text <> serial_ID Then
Sheet1.Cells(lastrow + 1, 4) = SN_TextBox1.Text
Sheet1.Cells(lastrow + 1, 1) = RMA_TextBox1.Text
Sheet1.Cells(lastrow + 1, 7) = ComboBox1.Text
End If
Next i
'this clears the fields of userform when button is clicked and saves it automatically
ActiveWorkbook.Save
Call resetform
End Sub
Try This.
Private Sub SubmitButton_Click()
Dim serial_ID As String
Dim cell As Range
Dim r As Range
serial_ID = UCase(Trim(SN_TextBox1.Value))
Worksheets("RMA Tracker").Activate
lastrow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
Set r = ActiveSheet.Cells(2, 4).Resize(lastrow, 1)
For Each cell In r:
If UCase(Trim(cell.Value)) = serial_ID Then
cell.Offset(0, 3).Value = ComboBox1.Value
GoTo aaaaa
End If
cell.Offset(1, 0).Value = serial_ID
cell.Offset(1, -3).Value = RMA_TextBox1.Text
cell.Offset(1, 3).Value = ComboBox1.Value
Next cell
aaaaa:
'this clears the fields of userform when button is clicked and saves it automatically
ActiveWorkbook.Save
Call resetform
End Sub

Excel Userform: Delete row when multiple criteria is met

I have 2 sheet on my excel workbook.
1 is Stock In sheet and 1 is Stock Out sheet.
I wish to store the information in Stock Out sheet when the data is found in Stock In.
Stock In sheet:
Stock Out sheet:
For example, the Stock Out sheet only will able to accept the data when the PT# and the Rack is tally with the detail in Stock In sheet.
As below will be the code for my delete button inside my userform:
Private Sub TrackOut_Click()
Sheets("Stock Out").Activate
Dim cDelete As VbMsgBoxResult
With Me
If Len(.TextBox1.Value) * Len(.PT.Value) *
Len(.Rack2.Value) * _
Len(.Operator2.Value) = 0 Then
MsgBox "Please Complete All Fields Before Submit"
Else
cDelete = MsgBox("Are you sure that you want to delete this record", vbYesNo + vbDefaultButton2, "Track Out")
If cDelete = vbYes Then
If Sheets("Stock In").Columns(2).Find(What:=PT.Text) Is Nothing Then
MsgBox "No stock inventory for this PT#"
Exit Sub
End If
eRow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Cells(eRow, 1).Value = TextBox1.Text
Cells(eRow, 2).Value = PT.Text
Cells(eRow, 3).Value = Rack2.Text
Cells(eRow, 4).Value = Operator2.Text
Else
If cDelete = vbNo Then
Unload Me
End If
End If
End If
End With
End Sub
OK - this is what I understand and what the code adjustment below does:
Operator completes a userform and inputs Date, PT#, Rack No and Operator. This gets looked-up in 'Stock In' sheet (all fields must match). If operator confirms then the record gets transferred to 'Stock Out' sheet on next available row and deleted from 'Stock In' sheet and other records moved up.
If you only want say two fields to match (userform and 'Stock In') then see the code for the adjustments to make: commented as '**
Private Sub TrackOut_Click()
Sheets("Stock Out").Activate
Dim cDelete As VbMsgBoxResult
Dim fndItm As Range
Dim orow As Long, irow As Long
Dim reqStock As String, itmStock As String
Dim stockArr(4) As String
With Me
If Len(.TextBox1.Value) * Len(.PT.Value) * Len(.Rack2.Value) * Len(.Operator2.Value) = 0 Then
MsgBox "Please Complete All Fields Before Submit."
Else
'collect requested (userform) data
'** reqStock should include those fields you require to match with Stock In record
'** currently set to check all fields
reqStock = .TextBox1.Value & .PT.Value & .Rack2.Value & .Operator2.Value
Set fndItm = Sheets("Stock In").Columns(2).Find(What:=PT.Text)
If Not fndItm Is Nothing Then
'if PT# found collect stock row data
With Sheets("Stock In")
irow = fndItm.Row
stockArr(0) = Format(.Cells(irow, 1).Value, "dd/mm/yyyy")
stockArr(1) = .Cells(irow, 2).Value
stockArr(2) = .Cells(irow, 3).Value
stockArr(3) = .Cells(irow, 4).Value
'** itmStock should include those fields you require to match with userform fields
'** these should match reqStock
'** currently set to check all fields
itmStock = stockArr(0) & stockArr(1) & stockArr(2) & stockArr(3)
End With
'compare requested (userfrom) data with Stock In data
If reqStock = itmStock Then
cDelete = MsgBox("Are you sure that you want to delete this record from stock?", vbYesNo) ' + vbDefaultButton2, _
"Track Out")
If cDelete = vbYes Then
'xfer record to Stock Out sheet
With Sheets("Stock Out")
orow = .Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
.Range(.Cells(orow, 1), .Cells(orow, 4)) = stockArr
End With
'delete record from Stock In sheet
With Sheets("Stock In")
.Range(.Cells(irow, 1), .Cells(irow, 4)).Delete xlShiftUp
End With
End If
'clear userform fields for next entry
.TextBox1.Value = ""
.PT.Value = ""
.Rack2.Value = ""
.Operator2.Value = ""
Else
MsgBox "PT# found but requested information does not match."
End If
Else
MsgBox "No stock inventory for this PT#."
Exit Sub
End If
End If
End With
End Sub

Resources