Delete Data from VBA Excel - excel

So currently i'm working on VBA forms(Product Master) , and got stuck across this problem. So basically, i have 3 buttons for my data i.e., Add, Update and Delete. Done with Add and Update button.
Just don't know how to delete my data from listbox which is in userform, and this user form is connected to a worksheet.
'''
Option Compare Text
Private Sub btn_ProductMaster_Add_Click()
If Me.txt_Product_Name.Value = "" Then
MsgBox "Please Enter Product Name", vbCritical
Exit Sub
End If
If IsNumeric(Me.txt_Purchase_Price) = False Then
MsgBox "Please Enter Product Price", vbCritical
Exit Sub
End If
If Me.txt_Product_colour.Value = "" Then
MsgBox "Please Enter Product Colour", vbCritical
Exit Sub
End If
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))
Me.txt_id = StrConv(Me.txt_Product_Name.Value, vbProperCase) & "_" & StrConv(Me.txt_Product_colour.Value, vbProperCase)
If Application.WorksheetFunction.CountIf(sh.Range("B:B"), Me.txt_id.Value) > 0 Then
MsgBox "This Product is already Available in product master", vbCritical
Exit Sub
End If
sh.Range("A" & lr + 1).Value = lr
sh.Range("B" & lr + 1).Value = Me.txt_id.Value
sh.Range("C" & lr + 1).Value = StrConv(Me.txt_Product_Name.Value, vbProperCase)
sh.Range("D" & lr + 1).Value = StrConv(Me.txt_Product_colour.Value, vbProperCase)
sh.Range("E" & lr + 1).Value = Me.txt_Purchase_Price.Value
Me.txt_id.Value = ""
Me.txt_Product_Name.Value = ""
Me.txt_Product_colour.Value = ""
Me.txt_Purchase_Price.Value = ""
MsgBox "Product has been added", vbInformation
Call show_data
End Sub
Sub show_data()
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))
If lr = 1 Then lr = 2
With Me.list_ProductMaster
.ColumnCount = 5
.ColumnHeads = True
.ColumnWidths = "40,110,110,80,80"
.RowSource = "Product_Master!A2:E" & lr
End With
End Sub
Private Sub btn_ProductMaster_Dlt_Click()
list_ProductMaster.SetFocus
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Me.txt_srno.Value
MsgBox lr
sh.Cells(lr + 1, "A").EntireRow.Delete
Me.txt_srno.Value = ""
Me.txt_id.Value = ""
Me.txt_Product_Name.Value = ""
Me.txt_Product_colour.Value = ""
Me.txt_Purchase_Price.Value = ""
MsgBox "Product has been Deleted", vbInformation
Call show_data
End Sub
Private Sub btn_ProductMaster_Extract_Click()
Dim nwb As Workbook
Set nwb = Workbooks.Add
ThisWorkbook.Sheets("Product_Master").UsedRange.Copy nwb.Sheets(1).Range("a1")
End Sub
Private Sub btn_ProductMaster_Updt_Click()
If Me.txt_Product_Name.Value = "" Then
MsgBox "Please Enter Product Name", vbCritical
Exit Sub
End If
If IsNumeric(Me.txt_Purchase_Price) = False Then
MsgBox "Please Enter Product Price", vbCritical
Exit Sub
End If
If Me.txt_Product_colour.Value = "" Then
MsgBox "Please Enter Product Colour", vbCritical
Exit Sub
End If
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Product_Master")
Dim lr As Integer
lr = Me.txt_srno.Value
Me.txt_id = StrConv(Me.txt_Product_Name.Value, vbProperCase) & "_" & StrConv(Me.txt_Product_colour.Value, vbProperCase)
sh.Range("A" & lr + 1).Value = lr
sh.Range("B" & lr + 1).Value = Me.txt_id.Value
sh.Range("C" & lr + 1).Value = StrConv(Me.txt_Product_Name.Value, vbProperCase)
sh.Range("D" & lr + 1).Value = StrConv(Me.txt_Product_colour.Value, vbProperCase)
sh.Range("E" & lr + 1).Value = Me.txt_Purchase_Price.Value
Me.txt_srno.Value = ""
Me.txt_id.Value = ""
Me.txt_Product_Name.Value = ""
Me.txt_Product_colour.Value = ""
Me.txt_Purchase_Price.Value = ""
MsgBox "Product has been Updated", vbInformation
Call show_data
End Sub
Private Sub list_ProductMaster_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Me.txt_srno.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 0)
Me.txt_id.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 1)
Me.txt_Product_Name.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 2)
Me.txt_Product_colour.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 3)
Me.txt_Purchase_Price.Value = Me.list_ProductMaster.List(Me.list_ProductMaster.ListIndex, 4)
End Sub
Private Sub UserForm_Activate()
Call show_data
End Sub
'''

Related

Delete row after application.match

I can't figure out why it is not deleting the row if the user selects no.
I even tried telling to delete a certain line in the ws but it still did not delete that row
Adding the data if it is not there works.
If it is already there the message box does pop up.
The only function that is not working is the delete.
Sub Submit_Data()
Application.ScreenUpdating = False
Dim App As New Excel.Application
Dim wBook As Excel.Workbook
Dim ws As Worksheet, id, v, m
Dim FileName As String
Dim CurrentJob As Long
Dim CurrentRow As Variant '<--- NOTE
Dim CurrentCell As Variant
Dim iRow As Long
FileName = ThisWorkbook.Path & "\database.xlsm"
'Check File Exist or Not
'If Dir(FileName) = "" Then
'MsgBox "Database File is missing. Unable to proceed.", vbOKOnly vbCritical, "Error"
'Exit Sub
'End If
Set wBook = App.Workbooks.Open(FileName)
App.Visible = False
If wBook.ReadOnly = True Then
TryWriteMode book:=wBook _
, numberOfTries:=4 _
, secondsWaitAfterFailedTry:=10
' MsgBox "test", vbInformation
End If
If wBook.ReadOnly Then
MsgBox "Database is in use. Please try again later.", vbOKOnly + vbInformation, "Read-only book"
Exit Sub
End If
'Transfer the Data
id = TextBox2.Value
With wBook.Sheets("database")
Set ws = wBook.Sheets("database")
' m = Application.Match(id, ws.[B:B], 0) 'try to match an existing row
m = Application.Match(id, 5, 0)
CurrentJob = TextBox2.Value
CurrentRow = Application.Match(CurrentJob, ws.Range("B:B"), 0)
CurrentCell = ws.Cells(CurrentRow, 1)
If IsError(CurrentRow) Then
iRow = .Range("A" & Application.Rows.Count).End(xlUp).Row + 1
.Range("A" & iRow).Value = TextBox1.Value 'Cell
.Range("B" & iRow).Value = TextBox2.Value 'workorder number
.Range("C" & iRow).Value = TextBox3.Value 'product number
.Range("D" & iRow).Value = TextBox4.Value 'Work order quanity
Else
MsgBox "JOB ALREADY ASSIGNED TO " & CurrentCell & vbNewLine & "DO YOU WANT TO KEEP IT THIER ", vbYesNo
If Result = vbNo Then
ws.Rows(CurrentRow).EntireRow.Delete
End If
End If
End With
wBook.Close Savechanges:=True
App.Quit
Set App = Nothing
'Reset the form
Call resetForm
Application.ScreenUpdating = True
End Sub

Excel MaxVal + 1 not ticking up when document is finished

im currently having an error code 1004 with VBA for excel, I'm not too familiar with the program but I have been able to determine the issue with the code although i definitely do not know how to fix it.
TLDR on what the code is supposed to do;
once the form is filled copy relevant data to a separate workbook
send an email to the relevant party of new entry
save the entry as a PDF
reset the workbook with the ticket number + 1 to mark up
the issue lies within the last step, once the first PDF file was created the workbook will no longer save as the ticker is stuck on Ticket# 1
Application.ScreenUpdating = False
If Range("H3").Value = "" Then MsgBox "Please Enter Device Serial Number"
Range("H3").Select
If Range("H3").Value = "" Then Exit Sub
If Range("M3").Value = "" Then MsgBox "Please Enter Reference Standard ID"
Range("M3").Select
If Range("M3").Value = "" Then Exit Sub
If Range("K9").Value = "" Then MsgBox "Please Enter Atleast One Dimensional Check"
Range("K9").Select
If Range("K9").Value = "" Then Exit Sub
If Range("Q9").Value = "" Then MsgBox "Please Enter Visual Check for Damage"
Range("Q9").Select
If Range("Q9").Value = "" Then Exit Sub
If Range("U9").Value = "" Then MsgBox "Please Enter Inital for Damage Check"
Range("U9").Select
If Range("U9").Value = "" Then Exit Sub
If Range("Q10").Value = "" Then MsgBox "Please Enter Visual Check for Wear"
Range("Q10").Select
If Range("Q10").Value = "" Then Exit Sub
If Range("U10").Value = "" Then MsgBox "Please Enter Inital for Wear Check"
Range("U10").Select
If Range("U10").Value = "" Then Exit Sub
If Range("Q11").Value = "" Then MsgBox "Please Enter Visual Check for Travel"
Range("Q11").Select
If Range("Q11").Value = "" Then Exit Sub
If Range("U11").Value = "" Then MsgBox "Please Enter Inital for Travel Check"
Range("U11").Select
If Range("U11").Value = "" Then Exit Sub
If Range("Q12").Value = "" Then MsgBox "Please Enter Visual Check for Zero"
Range("Q12").Select
If Range("Q12").Value = "" Then Exit Sub
If Range("U12").Value = "" Then MsgBox "Please Enter Inital for Zero Check"
Range("U12").Select
If Range("U12").Value = "" Then Exit Sub
If Range("Q13").Value = "" Then MsgBox "Please Enter Visual Check for Repeatability"
Range("Q13").Select
If Range("Q13").Value = "" Then Exit Sub
If Range("U13").Value = "" Then MsgBox "Please Enter Inital for Repeatability Check 3x"
Range("U13").Select
If Range("U13").Value = "" Then Exit Sub
If Range("C23").Value = "True" Then MsgBox "Please Check Final Verification Pass or Fail"
If Range("C23").Value = "True" Then Exit Sub
Workbooks.Open "\\192.168.150.31\Quality Control\Calibration\Periodic Verification\VerificationData(DONOTDELETE).xlsx"
Application.Run (["GetMax"])
Application.Run (["SavePrintEmail"])
Application.Run (["CopyClear"])
Application.ScreenUpdating = True
End Sub
Private Sub GetMax()
Dim WorkRange As Range
Dim MaxVal As Double
Workbooks("VerificationData(DONOTDELETE).xlsx").Activate
Set WorkRange = ActiveWorkbook.Worksheets("Data").Range("AK:AK")
MaxVal = WorksheetFunction.Max(WorkRange)
Workbooks("PIV-001.xlsm").Activate
ActiveWorkbook.Worksheets("PIV-001").Unprotect ("Moldamatic")
ActiveWorkbook.Worksheets("PIV-001").Range("U21").Value = MaxVal + 1
End Sub
Private Sub SavePrintEmail()
ThisWorkbook.Save
If Len(Dir("\\192.168.150.31\Quality Control\Calibration\Periodic Verification\" & Year(Date), vbDirectory)) = 0 Then
MkDir "\\192.168.150.31\Quality Control\Calibration\Periodic Verification\" & Year(Date)
End If
Sheets("PIV-001").Select
Sheets("PIV-001").ExportAsFixedFormat xlTypePDF, "\\192.168.150.31\Quality Control\Calibration\Periodic Verification\" & Year(Date) & "\" & Range("U21").Value & "-" & Year(Date), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.createitem(0)
On Error Resume Next
With OutMail
.To = "Spage#moldamatic.com"
.CC = ""
.BCC = ""
.Subject = "NEW INSTRUMENT VERFICATION (TICKET# " & Range("U21").Value & " INSTRUMENT ID# " & Range("H3").Value & " RESULT: " & Range("H22").Value & ")"
.HTMLBody = "An instrument has just been verfied, please see attached verification report. Verficiation results: " & Range("H22").Value & " "
.Attachments.Add "\\192.168.150.31\Quality Control\Calibration\Periodic Verification\" & Year(Date) & "\" & Range("U21").Value & "-" & Year(Date) & ".pdf"
.send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True
ThisWorkbook.Save
End Sub
Private Sub CopyClear()
'Change path to database in line below
Dim historyWks As Worksheet
Dim inputWks As Worksheet
Dim nextRow As Long
Dim oCol As Long
Dim myRng As Range
Dim myCopy As String
Dim myCell As Range
'cells to copy from Input sheet - some contain formulas
myCopy = "U21,C22,E22,H3,M3,B9,F9,I9,K9,B10,F10,I10,K10,B11,F11,I11,K11,B12,F12,I12,K12,B13,F13,I13,K13,Q9,U9,Q10,U10,Q11,U11,Q12,U12,Q13,U13,G17"
Set inputWks = ThisWorkbook.Worksheets("PIV-001")
Workbooks("VerificationData(DONOTDELETE).xlsx").Activate
Set historyWks = ActiveWorkbook.Worksheets("Data")
With historyWks
nextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
End With
With inputWks
Set myRng = .Range(myCopy)
End With
With historyWks
With .Cells(nextRow, "A")
.Value = Now
.NumberFormat = "mm/dd/yyyy hh:mm:ss"
End With
.Cells(nextRow, "B").Value = Application.UserName
oCol = 3
For Each myCell In myRng.Cells
historyWks.Cells(nextRow, oCol).Value = myCell.Value
oCol = oCol + 1
Next myCell
End With
Workbooks("PIV-001.xlsm").Activate
Range("H3,M3,B9,F9,K9,B10,F10,K10,B11,F11,K11,B12,F12,K12,B13,F13,K13,Q9,U9,Q10,U10,Q11,U11,Q12,U12,Q13,U13,G17").Select
Selection.ClearContents
ActiveSheet.CheckBoxes.Value = False
Range("H3:L3").Select
ThisWorkbook.Worksheets("PIV-001").Protect ("Moldamatic")
Workbooks("PIV-001.xlsm").Save
Workbooks("VerificationData(DONOTDELETE).xlsx").Activate
Workbooks("VerificationData(DONOTDELETE).xlsx").Save
Workbooks("VerificationData(DONOTDELETE).xlsx").Close
End Sub
the issue laid within the MaxVal string, changed the code to get rid of it
new code
Private Sub GetMax()
Dim WorkRange As Range
Workbooks("VerificationData(DONOTDELETE).xlsx").Activate
Set WorkRange = ActiveWorkbook.Worksheets("Data").Range("AK:AK")
Workbooks("PIV-001.xlsm").Activate
ActiveWorkbook.Worksheets("PIV-001").Unprotect ("Moldamatic")
ActiveWorkbook.Worksheets("PIV-001").Range("U21").Value =
Range("U21").Value + 1
End Sub

Looping for dynamic pictures

So I have created a dynamic selection list for excel using vba. see below
Below is the code
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Address = "$A$2" Then
Call PanggilPhoto
End If
End Sub
Sub PanggilPhoto()
Application.ScreenUpdating = False
Dim myObj
Dim Foto
Set myObj = ActiveSheet.DrawingObjects
For Each Foto In myObj
If Left(Foto.Name, 7) = "Picture" Then
Foto.Select
Foto.Delete
End If
Next
Dim CommodityName1 As String, CommodityName2 As String, T As String
myDir = ThisWorkbook.Path & "\"
CommodityName1 = Range("A2")
T = ".png"
Range("C15").Value = CommodityName
On Error GoTo errormessage:
ActiveSheet.Shapes.AddPicture Filename:=myDir & CommodityName1 & T, _
linktofile:=msoFalse, savewithdocument:=msoTrue, Left:=190, Top:=10, Width:=140,
Height:=90
errormessage:If Err.Number = 1004 Then
Exit Sub
MsgBox "File does not exist." & vbCrLf & "Check the name of the Commodity!"
Range("A2").Value = ""
Range("C10").Value = ""
End If
Application.ScreenUpdating = True
End Sub
foto is a predefined data list in the sheet.
So the question is instead of doing it for one cell how can I create a loop of some sort to do it for multiple cells? I need it to import mulitple images on one macro run
found a solution
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Address = "$A$2" Then
Call schedules
End If
End Sub
Sub schedules()
Worksheets("Picture").Activate
Application.ScreenUpdating = False
Dim myObj
Dim Foto
Set myObj = ActiveSheet.DrawingObjects
For Each Foto In myObj
If Left(Foto.Name, 7) = "Picture" Then
Foto.Select
Foto.Delete
End If
Next
Dim CommodityName1 As String, CommodityName2 As String, T1 As String, T2 As String
Dim i As Integer, j As Integer, k As Integer
j = 0
For i = 2 To 100
myDir = "C:\Users\User\Desktop\ESTIMATING SHEETS\test\rebar shapes" & "\"
CommodityName1 = Range("A" & i)
T1 = ".png"
On Error GoTo errormessage:
ActiveSheet.Shapes.AddPicture Filename:=myDir & CommodityName1 & T1, _
linktofile:=msoFalse, savewithdocument:=msoTrue, Left:=230, Top:=j, Width:=140, Height:=80
errormessage:
If Err.Number = 1004 Then
Exit Sub
MsgBox "File does not exist." & vbCrLf & "Check the name of the rebar!"
Range("A" & i).Value = ""
Range("C10").Value = ""
End If
Application.ScreenUpdating = True
i = i + 11
j = j + 190
Next i
End Sub

Updating form responses from one sheet to another

I created a data entry form in Excel.
I would like that input to be stored in another sheet (Table format).
Code I found online and modified:
Function ValidateForm() As Boolean
SellerSKU.BackColor = vbWhite
Description.BackColor = vbWhite
ValidateForm = True
If Trim(SellerSKU.Value) = "" Then
MsgBox "SKU can't be left blank.", vbOKOnly + vbInformation, "SKU"
SellerSKU.BackColor = vbRed
SellerSKU.Activate
ValidateForm = False
ElseIf Trim(Description.Value) = "" Then
MsgBox "Description can't be left blank.", vbOKOnly + vbInformation, "Description"
Description.BackColor = vbRed
Description.Activate
ValidateForm = False
End If
End Function
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
SellerSKU.Value = ""
SellerSKU.BackColor = vbWhite
Description.Value = ""
Description.BackColor = vbWhite
End Sub
Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
Dim iRow As Long
iRow = Sheets("Reference Sheet (Order Hist)").Range("A1048576").End(xlUp).Row + 1
If ValidateForm = True Then
With ThisWorkbook.Sheets("Reference Sheet (Order Hist)")
.Range("A" & iRow).Value = SellerSKU.Value
.Range("C" & iRow).Value = Description.Value
End With
Call Reset
Else
Application.ScreenUpdating = False
Exit Sub
End If
Application.ScreenUpdating = True
End Sub
When I hit "Enter" on the data entry form, the table on the other sheet does not get updated.
Also is it possible to clear the form every time an entry has been successfully made?
This worked for me. Re-organized and removed some of the repetition...
Private Sub CommandButton2_Click()
Dim iRow As Long, valErrors As String
valErrors = ValidationErrors() 'checks the form
If Len(valErrors) = 0 Then
'no errors - add the data
With ThisWorkbook.Worksheets("Reference Sheet (Order Hist)")
iRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
.Range("A" & iRow).Value = SellerSKU.Value
.Range("C" & iRow).Value = Description.Value
End With
ResetForm 'Call keyword is deprecated...
Else
MsgBox "One or more errors in form entries:" & vbLf & vbLf & valErrors, _
vbOKOnly + vbExclamation, "Check form data"
End If
End Sub
'check the form and return a listing of any errors
Function ValidationErrors() As String
Dim msg As String
CheckNonBlank SellerSKU, "SKU can't be left blank.", msg
CheckNonBlank Description, "Description can't be left blank.", msg
ValidationErrors = msg
End Function
'utility sub - check if a control has text, flag as error if missing,
' and add some text to the overall validation message
Sub CheckNonBlank(cntrl As Object, msgErr As String, ByRef msg As String)
Dim isErr As Boolean
isErr = Len(Trim(cntrl.Value)) = 0 'true if no content
ErrorFlag cntrl, isErr
If isErr And Len(msgErr) > 0 Then
msg = msg & IIf(Len(msg) > 0, vbLf, "") & msgErr 'append this error
End If
End Sub
Private Sub CommandButton1_Click()
ResetForm
End Sub
'clear textboxes and any error flags
Sub ResetForm()
SellerSKU.Value = ""
ErrorFlag SellerSKU, False
Description.Value = ""
ErrorFlag Description, False
End Sub
'flag a control as having a problem (pass False to second parameter to clear flag)
Sub ErrorFlag(cntrl As Object, Optional HasError As Boolean = True)
cntrl.BackColor = IIf(HasError, vbRed, vbWhite)
End Sub

How can I convert this code to late binding so my colleagues can use this program on excel 2016?

Private Sub Image2_Click()
End Sub
Private Sub cmdProduct_Change()
End Sub
Private Sub AvailableStocks_Click()
End Sub
Private Sub cmb_Product_Change()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Product_Master")
If Me.cmb_Product.Value = "" Or Me.cmb_Type.Value = "" Then Me.txt_Rate.Value = ""
Dim rate As Double ' Or String, not sure what your data is.
On Error Resume Next
rate = WorksheetFunction.VLookup(Me.cmb_Product, sh.Range("B:D"), 2, False)
On Error GoTo 0
Me.txt_Rate.Value = rate
On Error Resume Next
rate = WorksheetFunction.VLookup(Me.cmb_Product, sh.Range("B:D"), 3, False)
On Error GoTo 0
Me.txt_Rate.Value = rate
End Sub
Private Sub cmb_Type_Change()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Product_Master")
If Me.cmb_Product.Value = "" Or Me.cmb_Type.Value = "" Then Me.txt_Rate.Value = ""
If Me.cmb_Type.Value = "Sale" Then
Me.txt_Rate.Value = Application.WorksheetFunction.VLookup(Me.cmb_Product, sh.Range("B:D"), 2, 0)
ElseIf Me.cmb_Type.Value = "Purchase" Then
Me.txt_Rate.Value = Application.WorksheetFunction.VLookup(Me.cmb_Product, sh.Range("B:D"), 3, 0)
End If
End Sub
Private Sub CommandButton1_Click()
Call Add_Product_list
Call Show_Sale_Purchase_Data
Call Show_Inventory
Call Show_Numbers
End Sub
Private Sub CommandButton2_Click()
frm_ProductMaster.Show False
End Sub
Private Sub CommandButton3_Click()
ThisWorkbook.Save
MsgBox "Data Has been Saved"
End Sub
Private Sub CommandButton4_Click()
Call Show_Inventory
End Sub
Private Sub CommandButton5_Click()
Dim nwb As Workbook
Set nwb = Workbooks.Add
ThisWorkbook.Sheets("Inventory_Display").UsedRange.Copy nwb.Sheets(1).Range("A1")
End Sub
Private Sub CommandButton6_Click()
'''''''' Validation ''''''''''
If Me.cmb_Product.Value = "" Then
MsgBox "Please selet the Product", vbCritical
Exit Sub
End If
If IsNumeric(Me.txtQty) = False Then
MsgBox "Please enter correct QTY", vbCritical
Exit Sub
End If
If Me.cmb_Type.Value = "" Then
MsgBox "Please selet the Type", vbCritical
Exit Sub
End If
'''''''''''' Add Data
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sale_Purchase")
Dim lr As Long
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))
sh.Range("A" & lr + 1).Value = lr
sh.Range("B" & lr + 1).Value = Me.cmb_Product.Value
sh.Range("C" & lr + 1).Value = Me.cmb_Type.Value
sh.Range("D" & lr + 1).Value = Me.txtQty.Value
sh.Range("E" & lr + 1).Value = Me.txt_Rate.Value
sh.Range("F" & lr + 1).Value = Me.txt_Rate.Value * Me.txtQty.Value
If Me.cmb_Type.Value = "Purchase" Then
sh.Range("G" & lr + 1).Value = "NA"
Else
sh.Range("G" & lr + 1).Value = (Me.txt_Rate.Value * Me.txtQty.Value) - Application.WorksheetFunction.VLookup(Me.cmb_Product, ThisWorkbook.Sheets("Product_Master").Range("B:D"), 3, 0) * Me.txtQty.Value
End If
sh.Range("H" & lr + 1).Value = Me.txt_Date.Value
''''''''''' CLEAR BOXES
Me.cmb_Product.Value = ""
Me.cmb_Type.Value = ""
Me.cmb_Type.Value = ""
Me.txt_Rate.Value = ""
Call Show_Sale_Purchase_Data
Call Show_Inventory
Call Show_Numbers
MsgBox "Data has been added", vbInformation
End Sub
Private Sub CommandButton7_Click()
'''''''' Validation ''''''''''
If Me.cmb_Product.Value = "" Then
MsgBox "Please selet the Product", vbCritical
Exit Sub
End If
If IsNumeric(Me.txtQty) = False Then
MsgBox "Please enter correct QTY", vbCritical
Exit Sub
End If
If Me.cmb_Type.Value = "" Then
MsgBox "Please selet the Type", vbCritical
Exit Sub
End If
'''''''''''' Update Data
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sale_Purchase")
Dim lr As Long
lr = Me.txt_id.Value
sh.Range("A" & lr + 1).Value = lr
sh.Range("B" & lr + 1).Value = Me.cmb_Product.Value
sh.Range("C" & lr + 1).Value = Me.cmb_Type.Value
sh.Range("D" & lr + 1).Value = Me.txtQty.Value
sh.Range("E" & lr + 1).Value = Me.txt_Rate.Value
sh.Range("F" & lr + 1).Value = Me.txt_Rate.Value * Me.txtQty.Value
If Me.cmb_Type.Value = "Purchase" Then
sh.Range("G" & lr + 1).Value = "NA"
Else
sh.Range("G" & lr + 1).Value = (Me.txt_Rate.Value * Me.txtQty.Value) - Application.WorksheetFunction.VLookup(Me.cmb_Product, ThisWorkbook.Sheets("Product_Master").Range("B:D"), 3, 0) * Me.txtQty.Value
End If
sh.Range("H" & lr + 1).Value = Me.txt_Date.Value
''''''''''' CLEAR BOXES
Me.cmb_Product.Value = ""
Me.cmb_Type.Value = ""
Me.cmb_Type.Value = ""
Me.txt_Rate.Value = ""
Me.txt_id.Value = ""
Call Show_Sale_Purchase_Data
Call Show_Inventory
Call Show_Numbers
MsgBox "Data has been updated", vbInformation
End Sub
Private Sub CommandButton8_Click()
Dim nwb As Workbook
Set nwb = Workbooks.Add
ThisWorkbook.Sheets("Sale_Purchase_Display").UsedRange.Copy nwb.Sheets(1).Range("A1")
End Sub
Private Sub Image4_Click()
End Sub
Private Sub Image10_Click()
Call Calendar.SelectedDate(Me.txt_Date)
End Sub
Private Sub Image11_Click()
Call Calendar.SelectedDate(Me.txt_StartDate)
End Sub
Private Sub Image3_Click()
Call Calendar.SelectedDate(Me.txt_EndDate)
End Sub
Private Sub TxtEndDate_Change()
End Sub
Private Sub Image5_Click()
End Sub
Private Sub Image6_Click()
End Sub
Private Sub Image8_Click()
End Sub
Private Sub ListBox2_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Me.txt_id.Value = Me.ListBox2.List(Me.ListBox2.ListIndex, 0)
Me.cmb_Product.Value = Me.ListBox2.List(Me.ListBox2.ListIndex, 1)
Me.txtQty.Value = Me.ListBox2.List(Me.ListBox2.ListIndex, 3)
Me.cmb_Type.Value = Me.ListBox2.List(Me.ListBox2.ListIndex, 2)
Me.txt_Rate.Value = Me.ListBox2.List(Me.ListBox2.ListIndex, 4)
Me.txt_Date.Value = Format(Me.ListBox2.List(Me.ListBox2.ListIndex, 7), "D-MMM-YYYY")
End Sub
Private Sub OptionButton1_Click()
Call Show_Sale_Purchase_Data
End Sub
Private Sub OptionButton3_Click()
Call Show_Sale_Purchase_Data
End Sub
Private Sub OptionButton4_Click()
Call Show_Sale_Purchase_Data
End Sub
Private Sub txt_EndDate_Change()
End Sub
Private Sub UserForm_Initialize()
Me.txt_StartDate.Value = Format(Date, "D-MMM-YYYY")
Me.txt_EndDate.Value = Format(Date, "D-MMM-YYYY")
Me.txt_Date.Value = Format(Date, "D-MMM-YYYY")
'''''''''' Drop Down FOR TYPE
With Me.cmb_Type
.AddItem ""
.AddItem "Sale"
.AddItem "Purchase"
End With
Call Add_Product_list
Call Show_Sale_Purchase_Data
Call Show_Inventory
Call Show_Numbers
End Sub
Sub Add_Product_list()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Product_Master")
Dim i As Integer
Me.cmb_Product.Clear
Me.cmb_Product.AddItem ""
For i = 2 To Application.WorksheetFunction.CountA(sh.Range("A:A"))
Me.cmb_Product.AddItem sh.Range("B" & i)
Next i
End Sub
Sub Show_Sale_Purchase_Data()
Dim dsh As Worksheet
Dim sh As Worksheet
Set dsh = ThisWorkbook.Sheets("Sale_Purchase")
Set sh = ThisWorkbook.Sheets("Sale_Purchase_Display")
dsh.AutoFilterMode = False
dsh.Range("H:H").NumberFormat = "D-MMM-YYYY"
'''''''' PUTTING FILTER ''''''''
dsh.UsedRange.AutoFilter 8, ">=" & Me.txt_StartDate.Value, xlAnd, "<=" & Me.txt_EndDate.Value
If Me.OptionButton4.Value = True Then
dsh.UsedRange.AutoFilter 3, "Purchase"
End If
If Me.OptionButton3.Value = True Then
dsh.UsedRange.AutoFilter 3, "Sale"
End If
sh.UsedRange.Clear
dsh.UsedRange.Copy
sh.Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
dsh.AutoFilterMode = False
'''''''''''''''''' Display Data in Listbox
Dim lr As Long
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))
If lr = 1 Then lr = 2
With Me.ListBox2
.ColumnCount = 8
.ColumnHeads = True
.ColumnWidths = "0,190,70,70,70,70,70,70"
.RowSource = sh.Name & "!A2:H" & lr
End With
End Sub
Sub Show_Inventory()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Inventory")
sh.Cells.Clear
ThisWorkbook.Sheets("Product_Master").Range("B:B").Copy sh.Range("A1")
sh.Range("B1").Value = "Purchase"
sh.Range("C1").Value = "Sale"
sh.Range("D1").Value = "Available Stock"
sh.Range("E1").Value = "Stock Value"
Dim lr As Long
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))
If lr > 1 Then
sh.Range("B2").Value = "=SUMIFS(Sale_Purchase!D:D,Sale_Purchase!B:B,Inventory!A2,Sale_Purchase!C:C,""Purchase"")"
sh.Range("C2").Value = "=SUMIFS(Sale_Purchase!D:D,Sale_Purchase!B:B,Inventory!A2,Sale_Purchase!C:C,""Sale"")"
sh.Range("D2").Value = "=B2-C2"
sh.Range("E2").Value = "=VLOOKUP(A2,Product_Master!B:C,2,FALSE) *D2"
If lr > 2 Then
sh.Range("B2:E" & lr).FillDown
End If
sh.Calculate
End If
sh.UsedRange.Copy
sh.UsedRange.PasteSpecial xlPasteValues
Dim inv_Display As Worksheet
Set inv_Display = ThisWorkbook.Sheets("Inventory_Display")
inv_Display.Cells.Clear
If Me.txtSearch.Value <> "" Then
sh.UsedRange.AutoFilter 1, "*" & Me.txtSearch.Value & "*"
End If
sh.UsedRange.Copy inv_Display.Range("A1")
'''''''''''''''''''''' show data
lr = Application.WorksheetFunction.CountA(inv_Display.Range("A:A"))
If lr = 1 Then lr = 2
With Me.ListBox1
.ColumnCount = 5
.ColumnHeads = True
.ColumnWidths = "150,0,0,80,0"
.RowSource = inv_Display.Name & "!A2:E" & lr
End With
End Sub
Sub Show_Numbers()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Report")
sh.Range("C1").Value = Me.txt_StartDate.Value
sh.Range("C2").Value = Me.txt_EndDate.Value
sh.Calculate
Me.LblPurchase.Caption = sh.Range("C4").Value
Me.lbSale.Caption = sh.Range("C5").Value
Me.lblProfit.Caption = sh.Range("C6").Value
Me.lblInventory.Caption = sh.Range("C7").Value
Me.lblInventory1.Caption = sh.Range("C8").Value
End Sub
I have taught myself a good load of vba over the last couple of weeks to be able to program an inventory management system for my company. This is the final product and it runs perfectly on excel 2013. Now I need to convert it to late binding so my colleagues using excel 2016 can use it too. I cant figure out what to change and to what either.

Resources