Increment alphanumeric string automatically while submitting userform to Access database - excel

I am trying to shift from an excel database to an Access database to allow multi-user inputs.
I have a userform, which asks for user inputs, and it generates a file number for them by incrementing the last file number in the database. This is the working vba code for excel as database.
Sub Submit()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.AutomationSecurity = msoAutomationSecurityLow
If frmForm.txtDosage.Value = "" Or frmForm.txtProject.Value = "" Or frmForm.txtTime.Value = "" Then
MsgBox ("Complete All fields marked with (*) to proceed")
Else
Dim nwb As Workbook
Set nwb = Workbooks.Open("C:\Users\CHAMARA2.APNET\Automatic File Number Creation\AFNC Database.xlsm")
Dim emptyRow As Long
Dim lastinvoice As String
Dim newfile As String
emptyRow = WorksheetFunction.CountA(nwb.Sheets("Sheet1").Range("A:A")) + 1
lastinvoice = nwb.Sheets("Sheet1").Cells(emptyRow - 1, 7)
With nwb.Sheets("Sheet1")
.Cells(emptyRow, 1) = emptyRow - 1
.Cells(emptyRow, 2) = frmForm.txtProject.Value
.Cells(emptyRow, 3) = frmForm.txtDosage.Value
.Cells(emptyRow, 5) = frmForm.txtTime.Value
.Cells(emptyRow, 6) = Application.UserName
.Cells(emptyRow, 4) = frmForm.cmbPurpose.Value
.Cells(emptyRow, 7) = Left(lastinvoice, 4) & "-" & Format(Int(Right(lastinvoice, 3)) + 1, "000")
.Cells(emptyRow, 8) = Date
newfile = .Cells(emptyRow, 7).Value
End With
End If
MsgBox ("Your generated file number is " & newfile)
nwb.SaveAs Filename:="C:\Users\CHAMARA2.APNET\Automatic File Number Creation\AFNC Database.xlsm"
nwb.Close
End Sub
And this is the code for access:
Sub Submit2()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.AutomationSecurity = msoAutomationSecurityLow
If frmForm.txtDosage.Value = "" Or frmForm.txtProject.Value = "" Or frmForm.txtTime.Value = "" Then
MsgBox ("Complete All fields marked with (*) to proceed")
Else
Dim cnn As New ADODB.Connection 'dim the ADO collection class
Dim rst As New ADODB.Recordset 'dim the ADO recordset class
Dim dbPath As String
dbPath = "C:\Users\CHAMARA2.APNET\Downloads\TestDB.accdb"
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
Set rst = New ADODB.Recordset 'assign memory to the recordset
rst.Open Source:="FileNumbers", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
'Dim emptyRow As Long
'Dim lastinvoice As String
'Dim newfile As String
'emptyRow = WorksheetFunction.CountA(nwb.Sheets("Sheet1").Range("A:A")) + 1
'lastinvoice = nwb.Sheets("Sheet1").Cells(emptyRow - 1, 7)
With rst
.AddNew
.Fields("Project").Value = frmForm.txtProject.Value
.Fields("Dose").Value = frmForm.txtDosage.Value
.Fields("Time Point").Value = frmForm.txtTime.Value
.Fields("Submitted By").Value = Application.UserName
.Fields("Purpose").Value = frmForm.cmbPurpose.Value
.Fields("File Number").Value = Left(lastinvoice, 4) & "-" & Format(Int(Right(lastinvoice, 3)) + 1, "000")
.Fields("Date Created").Value = Date
.Update
'newfile = .Cells(emptyRow, 7).Value
End With
End If
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
MsgBox ("Your generated file number is " & newfile)
End Sub
How can I achieve something similar for the File Number field with the access code? And then getting the generated file number to the newfile variable as well, so that I can show it as a MsgBox.
This is the sequence of the file numbers: INHY-101, INHY-102, INHY-103 and so on
Please help

This is what worked for me:
Sub Submit2()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.AutomationSecurity = msoAutomationSecurityLow
If frmForm.txtDosage.Value = "" Or frmForm.txtProject.Value = "" Or frmForm.txtTime.Value = "" Then
MsgBox ("Complete All fields marked with (*) to proceed")
Else
Dim cnn As New ADODB.Connection 'dim the ADO collection class
Dim rst As New ADODB.Recordset 'dim the ADO recordset class
Dim dbPath As String
Dim qry As String
dbPath = "C:\Users\CHAMARA2.APNET\Downloads\TestDB.accdb"
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
Set rst = New ADODB.Recordset 'assign memory to the recordset
Set rs = New ADODB.Recordset
rst.Open Source:="FileNumbers", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
qry = "SELECT max(val(mid(File_Number,6))) FROM FileNumbers"
Set rs = cnn.Execute(qry)
newfile = "INHY-" & Format(rs.Fields(0) + 1, "000")
With rst
.AddNew
.Fields("Project").Value = frmForm.txtProject.Value
.Fields("Dose").Value = frmForm.txtDosage.Value
.Fields("Time Point").Value = frmForm.txtTime.Value
.Fields("Submitted By").Value = Application.UserName
.Fields("Purpose").Value = frmForm.cmbPurpose.Value
.Fields("File_Number").Value = newfile
.Fields("Date Created").Value = Date
.Update
End With
'cnn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
'Set rs = cnn.Execute("SELECT ##Identity", , adCmdText)
MsgBox ("Your generated file number is " & newfile)
End If
rst.Close
rs.Close
cnn.Close
Set rs = Nothing
Set rst = Nothing
Set cnn = Nothing
End Sub

Related

Visual Basic For Applications " subscript out of range" error

" I am getting a subscript out of range error after adding two new elements to an array. I remove the elements and re-run the code and it works. I need to know where to change the range so that it accommodates the array elements. This is the edited code: products = Array("BALANCER", "SKIN LIGHTENER", "FIRM AND FADE 6%", "FIRM AND FADE 8%")
After adding the two additional elements the error is thrown.
Research is showing that the array is the issue however after making adjustments the error message is still being thrown. "
"Here is the original code:"
Public Sub Dermesse_Dashboard(SD As Date, ED As Date)
Dim cn As ADODB.Connection
Dim rs As ADODB.RecordSet
Dim com As ADODB.Command
Dim ConnectionString As String, StoredProcName As String
Dim StartDate As ADODB.Parameter, EndDate As ADODB.Parameter, Product As ADODB.Parameter
Dim excelrange As String
Dim DateRange As String
Dim RCount As Integer
Dim products As Variant
products = Array("BALANCER", "SKIN LIGHTENER")
Set cn = New ADODB.Connection
Set rs = New ADODB.RecordSet
Set com = New ADODB.Command
Workbooks.Open ("\\apfssvr01\Arrow_RX\Reports\Templates\Dermesse_Dashboard(Template).xlsx")
ConnectionString = "Provider=sqloledb;Data Source=ARWSQL01;initial catalog=futurefill;User Id=endicia;Pwd=endicia;trusted_connection=yes;"
On Error GoTo CloseConnection
Application.ScreenUpdating = False
cn.Open ConnectionString
cn.CursorLocation = adUseClient
StoredProcName = "Dermesse_Shipped_by_Product"
With com
.ActiveConnection = cn
.CommandType = adCmdStoredProc
.CommandText = StoredProcName
End With
Set StartDate = com.CreateParameter("#StartDate", adDBTimeStamp, adParamInput, , SD)
com.Parameters.Append StartDate
Set EndDate = com.CreateParameter("#Enddate", adDBTimeStamp, adParamInput, , ED)
com.Parameters.Append EndDate
ActiveWorkbook.Sheets(2).Select
'loop through each item in products.
For Each i In products
'remove the product parameter if it exists so we can set it to the next product
If Product Is Nothing = False Then
com.Parameters.Delete (2)
End If
Set Product = com.CreateParameter("#Product", adVarChar, adParamInput, 200, i)
com.Parameters.Append Product
Set rs = com.Execute
'add rows to the excel table if the record set if 2 or greater.
'if we dont any tables below the first could be over written
If rs.RecordCount >= 2 Then
For j = 0 To rs.RecordCount - 3
ActiveSheet.ListObjects("Ship " & i).ListRows.Add (2)
Next
End If
ActiveSheet.ListObjects("Ship " & i).DataBodyRange.Select
Selection.CopyFromRecordset rs
rs.Close
Next
ActiveWorkbook.Sheets(6).Select
StoredProcName = "Dermesse_Shipped_wOrder"
With com
.ActiveConnection = cn
.CommandType = adCmdStoredProc
.CommandText = StoredProcName
End With
If Product Is Nothing = False Then
com.Parameters.Delete (2)
End If
Set Product = com.CreateParameter("#Product", adVarChar, adParamInput, 200, "Dermesse")
com.Parameters.Append Product
Set rs = com.Execute
RCount = rs.RecordCount
With ActiveSheet.ListObjects("Invoice DERMESSE")
If rs.RecordCount >= 2 Then
For j = 0 To rs.RecordCount - 3
.ListRows.Add (2)
Next
End If
.DataBodyRange.Select
Selection.CopyFromRecordset rs
.ListColumns(12).Range.Select
Selection.NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(#_)"
End With
rs.Close
cn.Close
'set a data fee value for each record. look at the order number of a specific line. if the line above or below are the same
'the data fee is 7.5 else is 10
r = 9
For i = 0 To RCount - 1
If ActiveSheet.Range("C" & r + i).Value = ActiveSheet.Range("C" & (r + i) - 1).Value Then
ActiveSheet.Cells(r + i, 12).Value = 7.5
ElseIf ActiveSheet.Range("C" & r + i).Value = ActiveSheet.Range("C" & (r + i) + 1).Value Then
ActiveSheet.Cells(r + i, 12).Value = 7.5
Else
ActiveSheet.Cells(r + i, 12).Value = 10
End If
Next i
If SD <> ED Then
DateRange = Format(SD, "yyyy-mm-dd") & " through " & Format(ED, "yyyy-mm-dd")
Else
DateRange = Format(SD, "yyyy-mm-dd")
End If
With ActiveWorkbook
For i = 1 To .Sheets.Count
.Sheets(i).Select
.Sheets(i).Range("A2").Value = DateRange
Next
.Sheets("Dermesse Dashboard").Select
End With
On Error GoTo 0
Application.DisplayAlerts = False
ActiveWorkbook.RefreshAll
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs ("\\apfssvr01\Arrow_RX\Reports\Dermesse\DERMESSE_Dashboard(" & DateRange & ").xlsx"), FileFormat:=51
Application.DisplayAlerts = True
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
frmSwitchboard.lblDD.Caption = "Report Complete"
Exit Sub
CloseConnection:
Application.ScreenUpdating = True
frmSwitchboard.lblDD.Caption = "Error: " & Error
cn.Close
If ActiveWorkbook.Sheets(1).Name <> "Sheet1" Then
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End If
End Sub
Any help would be greatly appreciated

Getting "Automation error" while updating a column through VBA

I have written a VBA code to update a column but getting Automation Error while running the program at line 41 which is Set rsf = cmd.Execute. Is the way of writing update statement incorrect in my code? Not getting what is the issue here. I'd appreciate any help towards a solution for my problem.
Private Sub Update_Visibility_Flag_Click()
Dim fldrpath As String
Dim currDate As String
Dim mePrgTrck As String
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim cnf As ADODB.Connection
Dim rsf As ADODB.Recordset
Dim sqlstr As String
fldrpath = "\\lp99dfd\groups$\Record Extracts\New folder\New folder\" & Format(Date, "yyyymm")
currDate = "PI_202008"
mePrgTrck = fldrpath & "\LE\Progress_Tracker_" & Format(Date, "yyyymm") & "_LE.xlsx"
Set wkb1 = Workbooks.Open(mePrgTrck)
Set sht1 = wkb1.Sheets(currDate)
Set cnf = New ADODB.Connection
Set rsf = New ADODB.Recordset
cnf.Open ( _
"User ID=AI_ZK_DTA" & _
";Password=aizkdta" & _
";Data Source=POIUY" & _
";Provider=OraOLEDB.Oracle")
For Each cell In sht1.Range("A2:A28")
If cell.Offset(0, 3).Value = "Success" Then
sqlstr = "UPDATE AI_" & cell.Value & "_DTA SET VISIBLE = 'Y'"
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnf
cmd.CommandType = adCmdText
cmd.Properties("PLSQLRSet") = True
cmd.CommandText = sqlstr
Set rsf = cmd.Execute
cmd.Properties("PLSQLRSet") = False
cell.Offset(0, 8).Value = cell.Offset(0, 8).Value & "| Done"
End If
Next cell
wkb1.Close True
Set rsf = Nothing
Set cnf = Nothing
End Sub

Front-End Excel and back-end access update data

I need a small help. I have an Access file name "DB_MLL.accdb" with table name "tblMLL" total 31 columns including primary key. I'm using front-end Excel and back-end access to fetch the data. I have two buttons to pull data from Acess and push back to access. Pulling data from access is working fine but pushing back is not working. I'm using the below codes. request you please guide me where I am doing wrong.
Sub PushTableToAccess()
Dim cnn As ADODB.Connection
Dim MyConn
Dim rst As ADODB.Recordset
Dim i As Variant, j As Variant
Dim Rw As Long
Sheets("Data").Activate
Rw = Range("A65536").End(xlUp).Row
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
With cnn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
End With
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:="tblMLL", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
'Load all records from Excel to Access.
For i = 3 To Rw
rst.AddNew
For j = 1 To 31
If Cells(i, j).Value = "" Then
rst(Cells(2, j).Value) = ""
Else
rst(Cells(2, j).Value) = Cells(i, j).Value
End If
Next j
rst.Update
Next i
' Close the connection
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
MsgBox "Data Upload Completed successfully."
End Sub
Your code seems to have a bit of a fix.
Sub PushTableToAccess()
Dim cnn As ADODB.Connection
Dim MyConn
Dim rst As ADODB.Recordset
Dim i As Variant, j As Variant
Dim Rw As Long
Dim strConn As String
Sheets("Data").Activate
Rw = Range("A65536").End(xlUp).Row
Set cnn = New ADODB.Connection
MyConn = ThisWorkbook.Path & Application.PathSeparator & TARGET_DB
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & MyConn
cnn.Open strConn
Set rst = New ADODB.Recordset
wirh rst
.CursorLocation = adUseServer
.Source = "tblMLL"
.Options = adCmdTable
.ActiveConnection = strConn
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Open
'Load all records from Excel to Access.
For i = 3 To Rw
.AddNew
For j = 1 To 31
If Cells(i, j).Value = "" Then
.Fields(Cells(2, j).Value) = ""
Else
.Fields(Cells(2, j).Value) = Cells(i, j).Value
End If
Next j
.Update
Next i
End With
' Close the connection
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
MsgBox "Data Upload Completed successfully."
End Sub

Replace TextBox.Value Excel with recordset Fields.Value from Access

let say i have 3 "SerialNoCubicle" number as a trigger; "8", "17", "18".
When the combobox.value is filled with one of those, then the rest of textbox.value will replaced from access database. The problem is, i could only do it for the first, which is if the value was "8" then textboxes.value is replaced. But if "17" or "18" the textbox.value still empty.
I could do it manually by changing
If txtSerialNoCubicle.Value = 8 or txtSerialNoCubicle.Value = 17 or _
txtSerialNoCubicle.Value = 18 then
but if the user input another value beside "8", "17", "18" for "SerialNoCubicle" then the code wont work for new value
Private Sub serialnocubicleDB()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
Dim sql1 As String
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ace.OLEDB.12.0; " & _
"Data Source=E:\Database.accdb"
Set rs = New ADODB.Recordset
sql1 = "Select * FROM tblspecification "
rs.Open sql1, cn
If txtSerialNoCubicle.Value = rs.Fields("SerialNoCubicle").Value Then
TextBox1.Value = rs.Fields("Project").Value
TextBox2.Value = rs.Fields("ProjectNo").Value
TextBox3.Value = rs.Fields("No&DateofDrw").Value
TextBox4.Value = rs.Fields("DrawingNumber").Value
TextBox5.Value = rs.Fields("NameofCubicle").Value
TextBox6.Value = rs.Fields("SingleLineLayout").Value
TextBox7.Value = rs.Fields("PlantofTest").Value
TextBox9.Value = rs.Fields("TypeofProduct").Value
TextBox10.Value = rs.Fields("IPofProduct").Value
TextBox11.Value = rs.Fields("Substation").Value
End If
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
Instead of querying the whole table, just get the record you want
Private Sub serialnocubicleDB()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
Dim sql1 As String
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ace.OLEDB.12.0; " & _
"Data Source=E:\Database.accdb"
Set rs = New ADODB.Recordset
'Query for the specific serial number
' should be probably using parameters here depending on your use case
sql1 = "Select * FROM tblspecification t where " & _
" t.SerialNoCubicle=" & txtSerialNoCubicle.Value
rs.Open sql1, cn
If Not rs.EOF Then
TextBox1.Value = rs.Fields("Project").Value
TextBox2.Value = rs.Fields("ProjectNo").Value
TextBox3.Value = rs.Fields("No&DateofDrw").Value
TextBox4.Value = rs.Fields("DrawingNumber").Value
TextBox5.Value = rs.Fields("NameofCubicle").Value
TextBox6.Value = rs.Fields("SingleLineLayout").Value
TextBox7.Value = rs.Fields("PlantofTest").Value
TextBox9.Value = rs.Fields("TypeofProduct").Value
TextBox10.Value = rs.Fields("IPofProduct").Value
TextBox11.Value = rs.Fields("Substation").Value
Else
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
TextBox5.Value = ""
TextBox6.Value = ""
TextBox7.Value = ""
TextBox9.Value = ""
TextBox10.Value = ""
TextBox11.Value = ""
End If
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub

MS Excel not updating with Access database. VB6

I have created a form in which when I click a button(subMnuPrintStaff), it should open an Excel file(WorkerNames.xls). The Excel file gets its records from my database(Employee.mdb). However, the problem is that when I update my databasefile(Employee.mdb), the records on my Excel file does not get updated. How do I fix this?
I am using flexgrid.
BUTTON CODE:
Private Sub subMnuPrintStaff_Click()
'On Error GoTo er
Dim oExcel As Object
Set oExcel = CreateObject("Excel.Application")
Dim oWorkBook As Object
Dim oWorkSheet As Object
Dim i As Integer, k As Integer
Dim lRow As Long
Dim LastRow As Long
Dim LastCol As Long
oExcel.Visible = False
oExcel.Workbooks.Open App.Path & "\WorkerNames.xls"
Set oWorkSheet = oExcel.Workbooks("WorkerNames.xls").Sheets("WorkerNames")
i = 2 'Row in Excel
LastRow = DataGrid1.Row 'Save Current row
LastCol = DataGrid1.Col 'and column
DataGrid1.Row = 0 'Fixed Row is -1
Do While DataGrid1.Row <= DataGrid1.VisibleRows - 1
For k = 1 To DataGrid1.Columns.Count - 1
DataGrid1.Col = k 'Fixed Column is -1
oWorkSheet.Cells(i, k).Font.Bold = False
oWorkSheet.Cells(i, k).Font.Color = vbBlack
oWorkSheet.Cells(i, k).Value = DataGrid1.Text
Next
i = i + 1
If DataGrid1.Row < DataGrid1.VisibleRows - 1 Then
DataGrid1.Row = DataGrid1.Row + 1
Else
Exit Do
End If
Loop
DataGrid1.Row = LastRow 'Restore original Row
DataGrid1.Col = LastCol 'and Column
oExcel.Workbooks("WorkerNames.xls").Save
oExcel.Workbooks("WorkerNames.xls").Close savechanges:=True
oExcel.Quit
'cmdView.Enabled = True
'er:
'If err.Number = 1004 Then
'Exit Sub
'End If
On Error GoTo ErrHandler
Dim xlApp As Object
Dim xlWB As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open("WorkerNames.xls")
Exit Sub
ErrHandler:
MsgBox "There is a problem opening that workbook!", vbCritical, "Error!"
End Sub
FORM LOAD CODE:
Dim oRs As New ADODB.Recordset
Dim adoConn2 As ADODB.Connection
Set adoConn2 = New ADODB.Connection
adoConn2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " & App.Path & "\Employee.mdb"
adoConn2.Open
oRs.CursorLocation = adUseClient
oRs.Open "select * from employeeName", adoConn2, adOpenKeyset, adLockPessimistic
Set DataGrid1.DataSource = oRs
DataGrid1.Refresh
Any help would be greatly appreciated. Database and Excel files are in the same directory with the project.
CODE FOR SAVING DATA INTO MY DATABASE - using text boxes
Dim adoConn As New ADODB.Connection Dim constr, curSql As String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & App.Path & "\employee.mdb;Persist Security Info=False"
Set adoConn = New ADODB.Connection
adoConn.ConnectionString = constr adoConn.Open
If txtFirstName.Text = "" Or txtLastName.Text = "" Then
MsgBox "Some fields are empty!", vbInformation + vbOKOnly, "Empty Fields"
Else curSql = "INSERT INTO employeename(Firstname, LastName) VALUES ("curSql = curSql & "'" & Replace(txtFirstName.Text, "'", "''") & "'," curSql = curSql & "'" & Replace(txtLastName.Text, "'", "''") & "')"
adoConn.Execute curSql
adoConn.Close
MsgBox "Data successfully added!", vbOKOnly, "Success!"
txtFirstName.Text = ""
txtLastName.Text = ""

Resources