Visual Basic For Applications " subscript out of range" error - excel

" 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

Related

ERROR - VBA Object doesnt support this property or method

Im trying to show the data from my database which is MS Access into my listview in VBA, but im getting that error. If i add this code "sh.Range("A2").copyfromrecorset rst" it shows the same error but if I remove that it works fine, but i think that code enable me to right under the header of the excel Anyone please help me? Thanks!
Sub List_Box_Data()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Support")
sh.Cells.ClearContents
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim qry As String, i As Integer
Dim n As Long
If Me.cb_filter.Value = "ALL" Then
qry = "Select * FROM TBL_CA"
ElseIf Me.cb_filter.Value = "Status" Then
qry = "Select * FROM TBL_CA Where " & Me.cb_filter.Value & " LIKE '%" & Me.tb_search.Value & "%'"
End If
cnn.Open "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\Database.ACCDB"
rst.Open qry, cnn, adOpenKeyset, adLockOptimistic
sh.Range("A2").copyfromrecorset rst
For i = 1 To rst.Fields.Count
sh.Cells(1, i).Value = rst.Fields(i - 1).Name
Next i
rst.Close
cnn.Close
'========================================
With Me.data_list
.ColumnCount = 10
.ColumnHeads = True
.ColumnWidths = "50,50,50,100,50,50,50,100,100,100,100,100,50,"
n = sh.Range("A" & Application.Rows.Count).End(xlUp).Row
If n > 1 Then
.RowSource = "Support!A2:N" & n
Else
.RowSource = "Support!A2:N2"
End If
End With
If (n - 1) < 2 Then
Me.lbl_record_count.Caption = (n - 1) & " Record"
ElseIf (n - 1) > 1 Then
Me.lbl_record_count.Caption = (n - 1) & " Records"
End If
End Sub

Increment alphanumeric string automatically while submitting userform to Access database

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

error: 'Application-defined or object-defined error' when using CopyFromRecordset - Excel macos

I am calling data from a PostgreSQL database into an Excel spreadsheet using the following macro:
Sub sub_copy_Recordset()
Dim objRecordset As Recordset
Dim strConnection As String
Dim input_portfolio, setRange As String
Dim end_date As Date
Dim i, record_count As Integer
input_portfolio = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(1, 1).Value
end_date = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(2, 1).Value
ini_date = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(3, 1).Value
On Error GoTo ErrHandler
strConnection = "Driver={PostgreSQL Unicode};Server=[ip];Port=5432;Database=[db];UID=user;PWD=[pwd];"
Set objConnection = New ADODB.Connection
Set objRecordset = New ADODB.Recordset
objRecordset.CursorLocation = adUseClient
objConnection.Open strConnection
With objRecordset
.ActiveConnection = objConnection
.Open "SELECT * FROM portfolio_positions('" & input_portfolio & "','" & end_date & "');"
End With
With ActiveWorkbook.Sheets("_tables")
.Range("A2").CopyFromRecordset objRecordset
record_count = objRecordset.RecordCount
objRecordset.Close
Set objRecordset = Nothing
End With
objConnection.Close
Set objConnection = Nothing
MsgBox "End Sub"
Exit Sub
ErrHandler:
Debug.Print Err.Number & " " & Err.Description
End Sub
When the macro executes the line where I copy the recordset to cell "A2" .Range("A2").CopyFromRecordset objRecordset it copies the data to A2 and jumps to the end of the Sub and executes line MsgBox "End Sub". When I add additional instructions below the CopyFromRecordset line as next:
Sub sub_copy_Recordset()
Dim objRecordset As Recordset
Dim strConnection As String
Dim input_portfolio, setRange As String
Dim end_date As Date
Dim i, record_count As Integer
input_portfolio = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(1, 1).Value
end_date = ActiveWorkbook.Sheets("_portfolio").Range("main").Cells(2, 1).Value
On Error GoTo ErrHandler
strConnection = "Driver={PostgreSQL Unicode};Server=79.143.185.46;Port=5432;Database=fincerec_canaima;UID=fincerec_user;PWD=_Or0cua1#;"
Set objConnection = New ADODB.Connection
Set objRecordset = New ADODB.Recordset
objRecordset.CursorLocation = adUseClient
objConnection.Open strConnection
With objRecordset
.ActiveConnection = objConnection
.Open "SELECT * FROM portfolio_positions('" & input_portfolio & "','" & end_date & "');"
End With
With ActiveWorkbook.Sheets("_tables")
.Range("A2").CopyFromRecordset objRecordset
record_count = objRecordset.RecordCount
objRecordset.Close
Set objRecordset = Nothing
.Columns("A").ColumnWidth = 20
.Columns("B").ColumnWidth = 5
With .Columns("C:G")
.ColumnWidth = 12
.NumberFormat = "#,##0.00"
.HorizontalAlignment = xlRight
End With
setRange = "A" & record_count + 2 & ":G1000"
.Range(setRange).ClearContents
setRange = "A2:G" & record_count + 1
.Names("_positionsRange").Delete
.Range(setRange).Name = "_positionsRange"
End With
objConnection.Close
Set objConnection = Nothing
MsgBox "End Sub"
Exit Sub
ErrHandler:
Debug.Print Err.Number & " " & Err.Description
End Sub
It copies the recordset in cell A2, but then jumps to ErrHandler: and then reports error
1004 Application-defined or object-defined error
Any help is appreciated.

"object invoked has disconnected from its clients" Excel 2016

I have seen this asked multiple times but none of the solutions offered have solved my issue- I continue to get this error even though I have used the same code in multiple other applications with no errors. I have included the code below and hope that someone can spot the issue that I am just failing to see!
Sub CreateJobsGraphsPrincipalCategory()
'Initial variables
Dim wbnew As Workbook
Dim wsnew As Worksheet
Dim Datasheet As Worksheet
'Dataset variables
Dim BeneficiaryList(0 To 10000), PrincipalList(0 To 10000), CheckRange As String
Dim NumberRows, RowNumber As Long
Dim Isduplicate, intPrincipal, intStatus, intLineItem As Integer
Dim PrincipalColumn, StatusColumn, LineItemColumn As String
Dim PrincipalRange, StatusRange, LineItemRange As String
Dim PrincipalNumber, BeneficiaryNumber As Integer
'New PivotChart variables
Dim objPivotcache As PivotCache
Dim objPivotTable As PivotTable
Dim bcount As Integer
Dim ProsperatorArray(1 To 25) As String
Dim BusinessNameColumn, BeneficiaryName, BeneficiaryNameFind As String
Dim objPivot As PivotTable, objPivotRange As Range, objChart As Chart
Dim LastColumnNumber As Double
'Setup workbooks
Dim CurrentWorkbook As Workbook
Dim SaveToWorkbook As Workbook
'Stop screen updating and calculating furing processing
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
'Select overall datasheet
Worksheets("DataforPrincipals").Activate
Set Datasheet = ActiveSheet
'Find last column. Start from column 30 as it will not be less than this
LastColumnNumber = 30
LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
While LastColumnValue <> ""
LastColumnNumber = LastColumnNumber + 1
LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
Wend
LastColumnNumber = LastColumnNumber - 1
'LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
LastColumnValue = Getcolumn(LastColumnNumber)
'get last row
LastRowNumber = 1
LastRowRange = "A" & LastRowNumber
LastRowValue = Datasheet.Cells(LastRowNumber, 1)
While LastRowValue <> ""
LastRowNumber = LastRowNumber + 1
LastRowRange = "A" & LastRowNumber
LastRowValue = Datasheet.Cells(LastRowNumber, 1)
Wend
LastRowNumber = LastRowNumber - 1
PivotRange = "A" & "1" & ":" & LastColumnValue & LastRowNumber
'Creating Pivot cache
Set objPivotcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'DataforPrincipals'!" & PivotRange)
'Create Arrays for Beneficiaries and Principals
'Get Columns for filtering and checking
PrincipalColumn = FindDataColumnHeading("Principal")
' StatusColumn = FindDataColumnHeading("Status")
LineItemColumn = FindDataColumnHeading("Line Item")
BusinessNameColumn = FindDataColumnHeading("Business Name")
RowNumber = 2
NumberRows = 0
CheckRange = BusinessNameColumn & RowNumber
PrincipalNumber = 1
BeneficiaryNumber = 1
While Datasheet.Range(CheckRange) <> ""
NumberRows = NumberRows + 1
PrincipalRange = PrincipalColumn & RowNumber
' StatusRange = StatusColumn & RowNumber
LineItemRange = LineItemColumn & RowNumber
' If Datasheet.Range(StatusRange) = "Active" Then
If Datasheet.Range(LineItemRange) = "Turnover" Then
BeneficiaryList(BeneficiaryNumber) = Datasheet.Range(CheckRange)
BeneficiaryNumber = BeneficiaryNumber + 1
'Check if principal is in the dataset yet
If RowNumber = 2 Then
PrincipalList(PrincipalNumber) = UCase(Trim(Datasheet.Range(PrincipalRange)))
Else
PrincipalNumber = PrincipalNumber + 1
Isduplicate = 0
For i = 1 To PrincipalNumber
If PrincipalList(i) = UCase(Trim(Datasheet.Range(PrincipalRange))) Then
Isduplicate = 1
End If
Next i
If Isduplicate = 0 Then
PrincipalList(PrincipalNumber) = UCase(Trim(Datasheet.Range(PrincipalRange)))
Else
PrincipalNumber = PrincipalNumber - 1
End If
End If
End If
' End If
RowNumber = RowNumber + 1
CheckRange = BusinessNameColumn & RowNumber
Wend
Set CurrentWorkbook = Application.ActiveWorkbook
' Set wbnew = Workbooks.Add
'wbnew = ActiveWorkbook.Name
CurrentWorkbook.Activate
For i = 1 To PrincipalNumber
PrincipalNameFind = PrincipalList(i)
If PrincipalList(i) <> PrincipalList(i - 1) Then
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
'Adding new worksheet
Worksheets("DataforPrincipals").Activate
Set wsnew = Worksheets.Add
wsnew.Name = PrincipalName & "JC"
Worksheets(PrincipalName & "JC").Activate
'Creating Pivot table
Set objPivotTable = objPivotcache.CreatePivotTable(wsnew.Range("A1"))
'set Beneficiary row field
'Setting Fields
With objPivotTable
With .PivotFields("Principal")
.Orientation = xlPageField
.CurrentPage = "ALL"
.ClearAllFilters
.CurrentPage = PrincipalNameFind
End With
'set data fields (PI TO, TO)
With .PivotFields("Category")
.Orientation = xlRowField
End With
.AddDataField .PivotFields("PI Total Staff"), "PI Jobs", xlSum
.AddDataField .PivotFields("Current Total Staff"), "Current Jobs", xlSum
.AddDataField .PivotFields("Job Growth"), "Job Growth ", xlSum
With .PivotFields("PI Jobs")
.NumberFormat = "#"
End With
With .PivotFields("Current Jobs")
.NumberFormat = "#"
End With
With .PivotFields("Job Growth ")
.NumberFormat = "#%"
End With
End With
' Access the new PivotTable from the sheet's PivotTables collection.
Set objPivot = ActiveSheet.PivotTables(1)
' Add a new chart sheet.
Set objChart = Charts.Add
' Create a Range object that contains
' all of the PivotTable data, except the page fields.
Set objPivotRange = objPivot.TableRange1
' Specify the PivotTable data as the chart's source data.
With objChart
.ShowAllFieldButtons = False
.SetSourceData objPivotRange
.ChartType = xlColumnClustered
.ApplyLayout (5)
With .ChartTitle
.Text = " Employment Growth performance per Category"
End With
.SeriesCollection(1).HasDataLabels = False
.SeriesCollection(2).HasDataLabels = False
.SeriesCollection(3).HasDataLabels = False
.Axes(xlCategory).HasTitle = False
.DataTable.Select
End With
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
ActiveSheet.Name = PrincipalName & " JCG"
If Sheetslist = "" Then
Sheetslist = PrincipalName & " JCG"
Else
Sheetslist = Sheetslist & ", " & PrincipalName & " JOBS"
End If
End If
Next i
'Copy to new file
Set CurrentWorkbook = Application.ActiveWorkbook
DirectoryName = Sheets("Run Automated").Range("B1")
For i = 1 To PrincipalNumber
If PrincipalList(i) <> PrincipalList(i - 1) Then
With Worksheets("Run Automated")
NameFileInitial = .Range("B2") & " " & PrincipalList(i) & ".xlsm"
End With
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
'Set sheets to save
sheet1save = PrincipalName & " TC"
sheet2save = PrincipalName & " TOC"
sheet7save = PrincipalName & "JC"
sheet8save = PrincipalName & " JCG"
Set CurrentWorkbook = Application.ActiveWorkbook
Namefile = DirectoryName & "\" & NameFileInitial
Workbooks.Open Namefile
Set SaveToWorkbook = Application.ActiveWorkbook
Application.DisplayAlerts = False
CurrentWorkbook.Sheets(Array(sheet1save, sheet2save, sheet7save, sheet8save)).Move Before:=SaveToWorkbook.Sheets(1)
ActiveWorkbook.Close (True)
Application.DisplayAlerts = True
CurrentWorkbook.Activate
End If
Next i
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
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