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
Related
I have an access connection file (.accdb) that allows me to use EXCEL (Office 365) to query a SharePoint Library. It all works great EXCEPT for new files added to that SharePoint Library. I can query for and return all data for these new files/entries but cannot get the filename for these new entries for some reason. Any help would be most appreciated.
Const SQLIMSSHAREPOINTCONNECTION = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\MORGAN\MACROS\IMS_SHAREPOINT_db.accdb"
Sub routine:
Dim i As Long
Dim cn As Object
Dim rs As Object
Dim StrSql As String
Dim thePieces1() As String
Dim thePieces2() As String
Dim theFullFilename As String
Dim theShortFilename As String
StrSql = "SELECT [Name], [ID], [PartNumber(s)], [DateCompleted], [DocumentType], " & _
"[WorkOrder(s)], [PurchaseOrder(s)], [SalesOrder(s)], [CustomerName(s)], [WorkCenter]" & _
" FROM [Inspection Reports]"
Set cn = CreateObject("ADODB.Connection")
cn.Open SQLIMSSHAREPOINTCONNECTION
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open StrSql
If Not (rs.BOF And rs.EOF) Then
i = 1
On Error Resume Next
Do While Not rs.EOF
i = i + 1
theFullFilename = ""
theShortFilename = ""
ReDim thePieces1(10)
thePieces1 = Split(rs.Fields(0), "#")
theFullFilename = thePieces1(1)
thePieces1() = Split(theFullFilename, "/")
theShortFilename = thePieces1(UBound(thePieces1))
Range("A" & i).Value = rs.Fields(1) ' ID
Range("B" & i).Value = theShortFilename ' Filename
Range("C" & i).Value = rs.Fields(2) ' PartNumber(s)
Range("D" & i).Value = rs.Fields(3) ' DateCompleted
Range("E" & i).Value = rs.Fields(4) ' DocumentType
Range("F" & i).Value = rs.Fields(5) ' WorkOrder(s)
Range("G" & i).Value = rs.Fields(6) ' PurchaseOrder(s)
Range("H" & i).Value = rs.Fields(7) ' CustomerName
Range("I" & i).Value = rs.Fields(8) ' WorkCenter
rs.MoveNext
Loop
It's not clear to me how your sharepoint access Excel connection works, but your recordset (rs) probably needs a refresh or requery after you updated the sharepoint data.
My macro works fine on a laptop with Windows 10 and Excel 2010. It also used to work fine on my desktop with Windows 10 and Excel 2010. Once my desktop got upgraded to Office 365, the macro throws a Type MisMatch error.
Following is the code where the error appears: intSteps = rs.RecordCount
Following is the module that is running. I'm wondering if the connection string needs to change with the upgrade to Office 365
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim strQuery As String
strQuery = ActiveSheet.Name
ActiveSheet.Unprotect
Columns("M:AA").Select
Selection.ClearContents
Rows("10:1000").Select
Selection.ClearContents
Dim i As Integer
Dim r As Long
Dim c As Integer
Dim x As Integer
Dim intSteps As Integer
Dim strSQL As String
Dim rs As ADODB.Recordset
Dim adoSQL As ADODB.Connection
Set adoSQL = New ADODB.Connection
adoSQL.Provider = "SQLOLEDB.1"
adoSQL.ConnectionString = "DATABASE=MainDB;SERVER=appsrv12.www.mysite.com;UID=User1;PWD=PW12;"
adoSQL.CursorLocation = adUseClient
adoSQL.Open
strStartDate = Range("dtStart").Value
strEndDate = Range("dtEnd").Value
strSQL = "SELECT * FROM tbl_Events WHERE DateTime >= '" & strStartDate & "' AND DateTime < '" & strEndDate & "' AND description like '% " & strQuery & "%' ORDER BY DateTime DESC"
Set rs = adoSQL.Execute(strSQL)
If rs.RecordCount > 0 Then
r = 32
x = rs.Fields.Count
For c = 1 To x
Range(Chr(Asc("B") + c - 1) & r).Value = rs.Fields(c - 1).Name
Next c
Range("B33").CopyFromRecordset rs
End If
intSteps = 0
i = 1
Dim n
Dim bolUseRecipe As Boolean
bolUseRecipe = False
For Each n In ActiveSheet.Names 'loop though all the named ranges
If Right(ActiveSheet.Names(i).Name, 8) = "RecipeID" Then
If Range("RecipeID").Value > 0 Then
bolUseRecipe = True
strSQL = "SELECT * FROM tbl_Recipe WHERE RecipeID = " & Range("RecipeID").Value & " ORDER BY StepNum"
Set rs = adoSQL.Execute(strSQL)
If rs.RecordCount > 0 Then
rs.MoveFirst
intSteps = rs.RecordCount '' LINE THAT THROWS THE ERROR
ReDim arrRecipe(1 To intSteps)
For i = 1 To rs.RecordCount
arrRecipe(i).StartTemp = rs.Fields("StartTemp")
arrRecipe(i).Hours = rs.Fields("Duration")
rs.MoveNext
DoEvents
Next i
End If
End If
Exit For
End If
i = i + 1
Next
Thanks in advance for your help or any suggestion to resolve my issue. I feel like it is something basic that I'm missing but not sure what it is at this time. Thanks again...
Try to use the following workaround:
rst = SomeRecordset
dim rstCount as Long
rstCount = CLng(rst.RecordCount)
See 'Type Mismatch' Error on ADODB.Recordset for more information.
" 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
I am trying to load data from an Excel file in a specific sheet into an ADODB.RecordSet via a VBA macro by using SQL SELECT command.
There are several columns on the Excel sheet, and I don't need all of them.
For example:
col.A = Surname, col.B = Name, col.C = IDPerson, [....columns that are not needed], Col.N = Boss
The purpose would be to get a recordset of aggregated data for:
col.C = IDPerson, col.N = Boss.
The fields highlighted in the image below.
I would like to have a RecordSet with the aggregated (non-repeating) data of the columns highlighted in yellow.
Obviously, this problem could also be solved by loading a matrix, but, in this case I would have to build a loading algorithm to "clean" any repetitions in the data and then later I would have to provide a search function with some loops.
So I thought that if I could load all the data I need by reading the WorkSheet as if it were a data table and then make a query on it to extract the data that I need and load everything in an ADODB.RecordSet would be much more efficient also for searching for data (filter data for example).
Below I report my code that loads all the data of my sheet:
Public Sub LoadRecordSet(ByVal LastRow As Long, ByVal LastCol As Integer)
Dim cnt As ADODB.Connection
Dim rsData As ADODB.Recordset
Dim strSQL As String
Dim strTMP As String
strTMP = Cells(LastRow, LastCol).Address
strTMP = Replace(strTMP, "$", "")
Set cnt = New ADODB.Connection
cnt.Mode = adModeRead
cnt.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ActiveWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";"
cnt.Open
strSQL = "SELECT * FROM [Sheet1$C2:" & strTMP & "]"
Set rsData = New ADODB.Recordset
With rsData
Set .ActiveConnection = cnt
.Source = strSQL
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
'TODO - Something with rsData for filtering or to research
'GC
If Not rsData Is Nothing Then
If rsData.State <> adStateClosed Then rsData.Close
Set rsData = Nothing
End If
If Not cnt Is Nothing Then
If cnt.State <> adStateClosed Then cnt.Close
Set cnt = Nothing
End If
End Sub
My question is: "What if I just want to load some columns as described above and aggregate them so they don't have repetitions in the data?"
For example if I want to load similar
SELECT [cod.fiscale], responsabile FROM [MySheet$A3:N480] GROUP BY [cod.fiscale], responsabile
It's possible?
Thank you so much.
I improved my code which is now working:
Public Sub CaricaDati()
Dim cnt As ADODB.Connection
Dim rsDati As ADODB.Recordset
Dim strSQL As String
Dim strTMP As String
Dim i As Integer
on Error GoTo Error_Handler
Range("A3").Select
g_BOLTS_UltimaRiga = LasRow
Call LastCol
strTMP = Cells(g_LastRow, g_LastCol).Address
strTMP = Replace(strTMP, "$", "")
Set cnt = New ADODB.Connection
cnt.Mode = adModeRead
cnt.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ActiveWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";"
cnt.Open
'strSQL = "SELECT * FROM [2$C2:" & strTMP & "]"
strSQL = "SELECT cf, responsabile FROM [2$C2:" & strTMP & "] GROUP BY cf, responsabile"
Set rsDati = New ADODB.Recordset
With rsDati
Set .ActiveConnection = cnt
.Source = strSQL
.CursorLocation = adUseClient
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open
End With
If Not (rsDati.BOF And rsDati.EOF) Then
strTMP = ""
For i = 0 To rsDati.Fields.Count - 1
strTMP = strTMP & rsDati.Fields(i).Name & ";"
Next i
Debug.Print strTMP
strTMP = ""
rsDati.MoveFirst
Do While Not rsDati.EOF
strTMP = ""
For i = 0 To rsDati.Fields.Count - 1
strTMP = strTMP & rsDati.Fields(i).Value & ";"
Next i
Debug.Print strTMP
rsDati.MoveNext
Loop
End If
Uscita:
On Error Resume Next
'GC
If Not rsDati Is Nothing Then
If rsDati.State <> adStateClosed Then rsDati.Close
Set rsDati = Nothing
End If
If Not cnt Is Nothing Then
If cnt.State <> adStateClosed Then cnt.Close
Set cnt = Nothing
End If
Exit Sub
Error_Handler:
On Error GoTo 0
MsgBox Err.Number & " - " & Err.Description, vbOKOnly + vbCritical, "ERRORE IMPREVISTO"
GoTo Uscita
End Sub
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 = ""