"Object was open" error for large result sets? - object

I am getting an error 'Object was open' when executing a stored procedure with large amounts of data. This procedure runs from a VB 6.00 application on SQL 2005. When running the script in SQL there is no problem
rs.Open cmd, Options:=adCmdStoredProc
IMPORTANT: This error ONLY happens with large amount of data. The threshold level is about 250000 rows of data. If more than that amount of data is retreived the error occurs. If less then there is no problem.
Any suggestion would be greatfull
Thanks

Try using other cursor types. On the connection object, try switching from adUseClient to adUseServer or vice versa.
rs.Open cmd, , adOpenStatic, adLockReadOnly, Options:=adCmdStoredProc

try use this module, it can help you avoid use recordSet for SQL procedure.
Notice Please use your own connection string to replace my connection string.
My code was designed for access database which db file ends with ".mdb"
Option Explicit
'//////////////////////////////////////////////////////////////////////////////
'##summary
'##require
'---Class:CHashTable.cls
'---Import:Microsoft ActiveX Data Objects 2.8 Library
'##reference
'##license
'##author sunsoft
'##create
'##modify
'---20160812:create this class
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Public Declare
'//
'//////////////////////////////////////////////////////////////////////////////
'------------------------------------------------------------------------------
' Interface
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public Const
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public DataType
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public Variable
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Public API
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Event Declare
'------------------------------------------------------------------------------
'//////////////////////////////////////////////////////////////////////////////
'//
'// Private Declare
'//
'//////////////////////////////////////////////////////////////////////////////
'------------------------------------------------------------------------------
' Private Const
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Private DataType
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Private Variable
'------------------------------------------------------------------------------
Private m_Conn As ADODB.Connection
Private m_Command As ADODB.Command
Private m_ConnString As String
Private m_FilePath As String
Private m_AutoConnect As Boolean
'------------------------------------------------------------------------------
' Property Variable
'------------------------------------------------------------------------------
'------------------------------------------------------------------------------
' Private API
'------------------------------------------------------------------------------
'//////////////////////////////////////////////////////////////////////////////
'//
'// Class
'//
'//////////////////////////////////////////////////////////////////////////////
'------------------------------------------------------------------------------
' Initialize
'------------------------------------------------------------------------------
Private Sub Class_Initialize()
m_ConnString = ""
m_FilePath = ""
m_AutoConnect = True
End Sub
'------------------------------------------------------------------------------
' Terminate
'------------------------------------------------------------------------------
Private Sub Class_Terminate()
Set m_Conn = Nothing
Set m_Command = Nothing
End Sub
'//////////////////////////////////////////////////////////////////////////////
'//
'// Events
'//
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Private Property
'//
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Private Methods
'//
'//////////////////////////////////////////////////////////////////////////////
Private Sub OpenConn()
Set m_Conn = New ADODB.Connection
m_Conn.CursorLocation = adUseClient
m_Conn.Open ConnectionString
End Sub
Private Sub CloseConn()
m_Conn.Close
Set m_Conn = Nothing
End Sub
Private Function m_ApostropheCount(ByVal SQL As String) As Long
'count number of "'"
m_ApostropheCount = Len(SQL) - Len(Replace(SQL, "'", ""))
End Function
Private Function m_ProcessNameParams(mSQL As String, mDic As CHashTable, mParams() As Variant) As Boolean
Dim mNewSql As String, mWord As String, mFieldName As String
Dim mParamCount As Long, i As Long, comaCount As Long
Dim mBeginParam As Boolean
If m_ApostropheCount(mSQL) Mod 2 = 1 Then
Err.Raise 110000000, "Symbal "" '"" must be in pairs,please check SQL statement"
End If
'init mDic
mBeginParam = False
mFieldName = ""
mParamCount = 0
For i = 1 To Len(mSQL)
mWord = Mid(mSQL, i, 1)
Select Case mWord
Case " ", ",", ")"
mNewSql = mNewSql & mWord
If mBeginParam Then
ReDim Preserve mParams(mParamCount)
mParams(mParamCount) = mDic.Item(mFieldName)
mFieldName = ""
mParamCount = mParamCount + 1
End If
mBeginParam = False
Case "'"
comaCount = comaCount + 1
mNewSql = mNewSql & mWord
Case "#"
If comaCount Mod 2 = 0 Then
mBeginParam = True
mNewSql = mNewSql & "?"
Else
'odd number of "'" means that "#" is only string of content
mNewSql = mNewSql & mWord
End If
Case Else
If mBeginParam = False Then
mNewSql = mNewSql & mWord
Else
mFieldName = mFieldName & mWord
End If
End Select
Next i
'all done but check last word for that last word maybe param
If mFieldName <> "" Then
ReDim Preserve mParams(mParamCount)
mParams(mParamCount) = mDic.Item(mFieldName)
mFieldName = ""
End If
'return
mSQL = mNewSql
m_ProcessNameParams = True
End Function
Private Function m_GetVarType(ByRef Value As Variant) As ADODB.DataTypeEnum
Select Case VarType(Value)
Case VbVarType.vbString
m_GetVarType = ADODB.DataTypeEnum.adVarWChar
Case VbVarType.vbInteger
m_GetVarType = ADODB.DataTypeEnum.adSmallInt
Case VbVarType.vbBoolean
m_GetVarType = ADODB.DataTypeEnum.adBoolean
Case VbVarType.vbCurrency
m_GetVarType = ADODB.DataTypeEnum.adCurrency
Case VbVarType.vbDate
m_GetVarType = ADODB.DataTypeEnum.adDate
Case 8209
m_GetVarType = ADODB.DataTypeEnum.adLongVarBinary
Case Else
m_GetVarType = ADODB.DataTypeEnum.adVariant
End Select
End Function
'//////////////////////////////////////////////////////////////////////////////
'//
'// Inherit
'//
'//////////////////////////////////////////////////////////////////////////////
'//////////////////////////////////////////////////////////////////////////////
'//
'// Public Property
'//
'//////////////////////////////////////////////////////////////////////////////
Public Property Get ConnectionString() As String
ConnectionString = m_ConnString
End Property
Public Property Let ConnectionString(ByVal vNewValue As String)
m_ConnString = vNewValue
End Property
Public Property Get IsReady() As Boolean
IsReady = IIf(Len(ConnectionString) > 0, True, False)
End Property
'//////////////////////////////////////////////////////////////////////////////
'//
'// Public Methods
'//
'//////////////////////////////////////////////////////////////////////////////
'---------------------Data Base Connection
Public Function DbConnFromFile(ByVal filePath As String) As ADODB.Connection
Dim mConn As New ADODB.Connection
mConn.CursorLocation = adUseClient
mConn.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";"
Set DbConnFromFile = mConn
End Function
Public Sub SetConnToFile(ByVal filePath As String)
m_ConnString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";"
End Sub
Public Sub SetConnToAccdb(ByVal filePath As String)
m_ConnString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Persist Security Info=False"
End Sub
Public Sub OpenDB()
m_AutoConnect = False
Call OpenConn
End Sub
Public Sub CloseDB()
m_AutoConnect = True
Call CloseConn
End Sub
'---------------------Querys
Public Function ExecQuery(ByVal SQL As String) As ADODB.Recordset
Dim mRes As New ADODB.Recordset
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
Set mRes = m_Command.Execute()
'disconnect from database
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set ExecQuery = mRes
Set m_Command = Nothing
End Function
Public Function ExecParamQuery(ByVal SQL As String, _
ParamArray Params()) As ADODB.Recordset
Dim mRes As ADODB.Recordset
Dim mParamArr As Variant, mParam As Variant
Dim i As Long
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
mParamArr = Params
If VarType(Params(0)) = 8204 Then
mParamArr = Params(0)
End If
With m_Command
For Each mParam In mParamArr
Dim Para As ADODB.Parameter
Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
Para.Value = mParam
If VarType(mParam) = vbEmpty Then
Para.size = 1
ElseIf VarType(mParam) = vbString Then
If LenB(mParam) = 0 Then
Para.size = 1
End If
End If
.Parameters.Append Para
Next
End With
Set mRes = m_Command.Execute()
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set ExecParamQuery = mRes
Set m_Command = Nothing
End Function
Public Function ExecNamedQuery(ByVal SQL As String, HashedParams As CHashTable) As ADODB.Recordset
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
Set ExecNamedQuery = ExecParamQuery(SQL, mParams)
End Function
Public Function ExecNonQuery(ByVal SQL As String) As Long
Dim affectedRows As Long
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
m_Command.Execute affectedRows
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
ExecNonQuery = affectedRows
End Function
Public Function ExecParamNonQuery(ByVal SQL As String, ParamArray Params()) As Long
Dim i As Long, affectedRows As Long
Dim mParamArr As Variant, mParam As Variant
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
mParamArr = Params
If VarType(Params(0)) = 8204 Then
mParamArr = Params(0)
End If
With m_Command
For Each mParam In mParamArr
Dim Para As ADODB.Parameter
Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
Para.Value = mParam
If VarType(mParam) = vbEmpty Then
Para.size = 1
ElseIf VarType(mParam) = vbString Then
If LenB(mParam) = 0 Then
Para.size = 1
End If
End If
.Parameters.Append Para
Next
End With
m_Command.Execute affectedRows
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
ExecParamNonQuery = affectedRows
End Function
Public Function ExecNamedNonQuery(ByVal SQL As String, HashedParams As CHashTable) As Long
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
ExecNamedNonQuery = ExecParamNonQuery(SQL, mParams)
End Function
Public Function ExecCreate(ByVal SQL As String) As Variant
Dim mRes As ADODB.Recordset
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
m_Command.Execute
m_Command.CommandText = "SELECT ##identity"
Set mRes = m_Command.Execute
If mRes.RecordCount > 0 Then
ExecCreate = mRes.Fields(0).Value
Else
ExecCreate = Empty
End If
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
Set mRes = Nothing
End Function
Public Function ExecParamCreate(ByVal SQL As String, ParamArray Params()) As Variant
Dim mParamArr As Variant, mParam As Variant
Dim mRes As ADODB.Recordset
Dim i As Long
Set m_Command = New ADODB.Command
If m_AutoConnect Then
Call OpenConn
End If
m_Command.ActiveConnection = m_Conn
m_Command.CommandText = SQL
m_Command.CommandType = adCmdText
mParamArr = Params
If VarType(Params(0)) = 8204 Then
mParamArr = Params(0)
End If
With m_Command
For Each mParam In mParamArr
Dim Para As ADODB.Parameter
Set Para = .CreateParameter(CStr(i), m_GetVarType(mParam), adParamInput, LenB(mParam))
Para.Value = mParam
If VarType(mParam) = vbEmpty Then
Para.size = 1
ElseIf VarType(mParam) = vbString Then
If LenB(mParam) = 0 Then
Para.size = 1
End If
End If
.Parameters.Append Para
Next
End With
m_Command.Execute
m_Command.CommandText = "SELECT ##identity"
Set mRes = m_Command.Execute
If mRes.RecordCount > 0 Then
ExecParamCreate = mRes.Fields(0).Value
Else
ExecParamCreate = Empty
End If
If m_AutoConnect Then
Call CloseConn
End If
Set m_Command = Nothing
Set mRes = Nothing
End Function
Public Function ExecNamedCreate(ByVal SQL As String, HashedParams As CHashTable) As Variant
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
ExecNamedCreate = ExecParamCreate(SQL, mParams)
End Function
Public Function ExecScalar(ByVal SQL As String) As Variant
Dim mRes As ADODB.Recordset
Set mRes = ExecQuery(SQL)
If mRes.RecordCount <= 0 Then
ExecScalar = Empty
Else
ExecScalar = mRes.Fields(0).Value
End If
Set mRes = Nothing
End Function
Public Function ExecParamScalar(ByVal SQL As String, _
ParamArray Params()) As Variant
Dim mRes As ADODB.Recordset
If VarType(Params(0)) = 8204 Then
Params = Params(0)
End If
Set mRes = ExecParamQuery(SQL, Params)
If mRes.RecordCount <= 0 Then
Set ExecParamScalar = Nothing
Else
ExecParamScalar = mRes.Fields(0).Value
End If
Set mRes = Nothing
End Function
Public Function ExecNamedScalar(ByVal SQL As String, HashedParams As CHashTable) As Variant
Dim mParams() As Variant
m_ProcessNameParams SQL, HashedParams, mParams
ExecNamedScalar = ExecParamScalar(SQL, mParams)
End Function
'---------------------Table Structure
Public Function Tables() As ADODB.Recordset
Dim mRes As ADODB.Recordset
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaTables)
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set Tables = mRes
End Function
Public Function UserTables() As ADODB.Recordset
Dim mRes As ADODB.Recordset
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaTables)
mRes.Filter = "table_type = 'TABLE'"
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set UserTables = mRes
End Function
Public Function Fields(ByVal TableName As String) As ADODB.Recordset
Dim mRes As ADODB.Recordset
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaColumns)
mRes.Filter = "table_name = '" & TableName & "'"
mRes.Sort = "ORDINAL_POSITION ASC"
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
Set Fields = mRes
End Function
Public Function KeyField(ByVal TableName As String) As String
Dim mRes As ADODB.Recordset
Dim mKeyFieldName As String
If m_AutoConnect Then
Call OpenConn
End If
Set mRes = m_Conn.OpenSchema(adSchemaPrimaryKeys)
mRes.Filter = "table_name = '" & TableName & "'"
mRes.ActiveConnection = Nothing
If m_AutoConnect Then
Call CloseConn
End If
If mRes.RecordCount > 0 Then
mRes.MoveFirst
Do While Not mRes.EOF
If mRes.Fields("column_name").Value <> "" Then
mKeyFieldName = mRes.Fields("column_name").Value
Exit Do
End If
Loop
End If
KeyField = mKeyFieldName
End Function
Public Sub ReleaseRecordset(res As ADODB.Recordset)
Set res = Nothing
End Sub

Related

excel vba not converting tamplate to word document

When I try to generate a word document, it gets stopped at the 80% progress bar and it shows the following error.
When I try to debug it, I see this
I'm getting error in now For i = 1 To .InlineShapes.Count
My code
Sub FillABookmark(strBM As String, strText As String)
Dim j As Long
With ActiveDocument
.Bookmarks(strBM).Range _
.InlineShapes _
.AddPicture FileName:=strText
j = ActiveDocument.InlineShapes.Count
.InlineShapes(j).Select
.Bookmarks.Add strBM, Range:=Selection.Range
End With
End Sub
Sub AddImage(strFile As String, addOrAfter As Boolean)
Dim oImage As Object
'Dim oDialog As Dialog
' Dim oRng As Object
' Set oDialog = Dialogs(wdDialogInsertPicture)
' With oDialog
' .Display
' If .Name <> "" Then
' strFile = .Name
' End If
'End With
'Selection.Move 6, -1 'moverse al principio del documento
'Selection.Find.Execute FindText:="[aud_sig_1]"
'If Selection.Find.Found = True Then
If (addOrAfter) Then
Set oImage = Selection.InlineShapes.AddPicture(strFile, False, True)
'With oRng
' .RelativeHorizontalPosition = _
' wdRelativeHorizontalPositionPage
' .RelativeVerticalPosition = _
' wdRelativeVerticalPositionPage
'.Left = CentimetersToPoints(0)
'.Top = CentimetersToPoints(4.5)
'End With
Else
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Set oImage = Selection.InlineShapes.AddPicture(strFile, False, True)
End If
With oImage
.LockAspectRatio = msoFalse
.Height = CentimetersToPoints(1.5)
.Width = CentimetersToPoints(2.1)
Set oRng = .ConvertToShape
End With
Set oDialog = Nothing
Set oImage = Nothing
Set oRng = Nothing
End Sub
Sub PicWithCaption(xPath, Optional ByVal imgType As String = "All")
Dim xFileDialog As FileDialog
Dim xFile As Variant
Dim doc As Document
'******Test
'Set doc = Application.ActiveDocument
'xPath = "C:\phototest\"
'doc.Bookmarks.Exists ("photos")
'doc.Bookmarks("photos").Select 'select the bookmark
'*****End test
Dim x, w, c
Dim oTbl As Word.Table, i As Long, j As Long, k As Long, StrTxt As String
Set oTbl = Selection.Tables.Add(Selection.Range, 2, 3)
With oTbl
.AutoFitBehavior (wdAutoFitFixed)
.Columns.Width = CentimetersToPoints(9)
'Format the rows
Call FormatRows(oTbl, 1)
End With
If xPath <> "" Then
xFile = Dir(xPath & "\*.*")
i = 1
CaptionLabels.Add Name:="Picture"
Do While xFile <> ""
If (UCase(Right(xFile, 3)) = "PNG" Or _
UCase(Right(xFile, 3)) = "TIF" Or _
UCase(Right(xFile, 3)) = "JPG" Or _
UCase(Right(xFile, 3)) = "GIF" Or _
UCase(Right(xFile, 3)) = "BMP") And (imgType = "All" Or UCase(Left(xFile, 1) <> imgType)) Then
j = Int((i + 2) / 3) * 2 - 1
k = (i - 1) Mod 3 + 1
'Add extra rows as needed
If j > oTbl.Rows.Count Then
oTbl.Rows.Add
oTbl.Rows.Add
Call FormatRows(oTbl, j)
End If
'Insert the Picture
'Dim shape As InlineShape
' ActiveDocument.InlineShapes.AddPicture _
' FileName:=xPath & "\" & xFile, LinkToFile:=False, _
' SaveWithDocument:=True, Range:=oTbl.Rows(j).Cells(k).Range
Set shape = ActiveDocument.InlineShapes.AddPicture(xPath & "\" & xFile, False, True, oTbl.Rows(j).Cells(k).Range)
oTbl.Rows(j).Cells(k).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
' With shape
' .LockAspectRatio = msoTrue
' If .Width > .Height Then
' .Height = InchesToPoints(1.75)
' Else
' .Width = InchesToPoints(1.75)
' End If
' End With
'shape.ScaleWidth = 50
'Get the Image name for the Caption
'StrTxt = Split(xPath & "\" & xFile, "\")(UBound(Split(.SelectedItems(i), "\")))
StrTxt = xFile
StrTxt = ": " & Split(StrTxt, ".")(0)
'Insert the Caption on the row below the picture
With oTbl.Rows(j + 1).Cells(k).Range
.InsertBefore vbCr
.Characters.First.InsertParagraph
.InsertBefore StrTxt
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Font.Bold = True
.Characters.First = vbNullString
.Characters.Last.Previous = vbNullString
End With
End If
i = i + 1
xFile = Dir()
Loop
End If
'End If
End Sub
Sub FormatRows(oTbl As Table, x As Long)
With oTbl
With .Rows(x)
.Height = CentimetersToPoints(6)
.HeightRule = wdRowHeightExactly
.Range.Style = "Normal"
.Alignment = wdAlignRowCenter
End With
With .Rows(x + 1)
.Height = CentimetersToPoints(1.2)
.HeightRule = wdRowHeightExactly
.Range.Style = "Caption"
.Alignment = wdAlignRowCenter
End With
End With
End Sub
Sub rezie()
Dim i As Long
With ThisDocument
For i = 1 To .InlineShapes.Count
Next i
End With
End Sub
Use the style enums to be on the safe side when on a non-english system:
.Range.Style = Word.wdStyleCaption (in case you are using early binding - what you are using)
In case of late binding: .Range.style = -35

VBA, data is not populating in new columns. Possible issue with Advanced Filter

We have added 5 new columns to three sheets in a workbook. The first sheet is like a staging table that then populates the other two. The problem is the new columns are not being populated with the data in the two final sheets. The data is visible in the intial sheet. I think it may be an issue with the Advanced Filter but im not sure. Any help would be appreciated.
Public Sub RunExtract()
Dim strExtractYear As String
Dim strExtractMonth As String
Dim strOutputFolder As String
Application.ScreenUpdating = False
'grab the control variable values
strExtractYear = Range("Extract_Year").Value
strExtractMonth = Range("Extract_Month").Value
strOutputFolder = Range("Output_Folder").Value
'pull the data
Application.StatusBar = "Pulling data..."
Call PullData(strExtractYear, strExtractMonth)
'filter and output the results
Application.StatusBar = "Extracting 310 summary data..."
Range("SummaryFilter.Criteria").Cells(2, 2).Formula = "=""=310"""
Call FilterData(Range("SalesExtract.Table"), Range("SummaryFilter.Criteria"), Range("SummaryFilter.Header"), "SummaryFilter.Table")
Call OutputResults("SUMMARY", "310", strOutputFolder)
Application.StatusBar = "Extracting 430 summary data..."
Range("SummaryFilter.Criteria").Cells(2, 2).Formula = "=""=430"""
Call FilterData(Range("SalesExtract.Table"), Range("SummaryFilter.Criteria"), Range("SummaryFilter.Header"), "SummaryFilter.Table")
Call OutputResults("SUMMARY", "430", strOutputFolder)
Application.StatusBar = "Extracting 310 detail data..."
Range("DetailFilter.Criteria").Cells(2, 2).Formula = "=""=310"""
Call FilterData(Range("SalesExtract.Table"), Range("DetailFilter.Criteria"), Range("DetailFilter.Header"), "DetailFilter.Table")
Call OutputResults("DETAIL", "310", strOutputFolder)
Application.StatusBar = "Extracting 430 detail data..."
Range("DetailFilter.Criteria").Cells(2, 2).Formula = "=""=430"""
Call FilterData(Range("SalesExtract.Table"), Range("DetailFilter.Criteria"), Range("DetailFilter.Header"), "DetailFilter.Table")
Call OutputResults("DETAIL", "430", strOutputFolder)
Call CleanUpThisWorkbook
Application.StatusBar = "Done"
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Public Sub PullData(ExtractYear As String, ExtractMonth As String)
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strStartDate As String
Dim strStartDateTime As String
Dim strEndDateTime As String
Dim strYear As String
Dim strMonth As String
Dim strLastDay As String
'clear the existing range
Range("SalesExtract.Table").CurrentRegion.Offset(1).EntireRow.Delete
'figure out the start and end datetimes
strYear = ExtractYear
strMonth = Right("0" & ExtractMonth, 2)
strStartDate = "{year}-{month}-{day}"
strStartDate = Replace(strStartDate, "{year}", strYear)
strStartDate = Replace(strStartDate, "{month}", strMonth)
strStartDate = Replace(strStartDate, "{day}", "01")
strStartDateTime = strStartDate & " 00:00:00"
strLastDay = CStr(Day(DateSerial(Year(strStartDate), Month(strStartDate) + 1, 0)))
strEndDateTime = "{year}-{month}-{day} 23:59:59"
strEndDateTime = Replace(strEndDateTime, "{year}", strYear)
strEndDateTime = Replace(strEndDateTime, "{month}", strMonth)
strEndDateTime = Replace(strEndDateTime, "{day}", strLastDay)
Private Sub OutputResults(Level As String, Company As String, Directory As String)
Dim wb As Workbook
Set wb = Workbooks.Add
Dim strSheet As String
If Level = "SUMMARY" Then
strSheet = "SummaryFilter"
ElseIf Level = "DETAIL" Then
strSheet = "DetailFilter"
Else
'raise error
End If
Call ThisWorkbook.Worksheets(strSheet).Range(strSheet & ".Table").Copy
Call wb.Worksheets(1).Range("A1").PasteSpecial(xlPasteValues)
Call ThisWorkbook.Worksheets(strSheet).Range(strSheet & ".ReplacementHeader").Copy
Call wb.Worksheets(1).Range("A1").PasteSpecial(xlPasteValues)
wb.Worksheets(1).Name = Level & " " & Company
Application.DisplayAlerts = False
Call wb.SaveAs(Directory & "\Sales Extract - " & Level & " " & Company & ".xlsx")
Application.DisplayAlerts = True
Call wb.Close
Set wb = Nothing
End Sub
Private Sub FilterData(FilterRng As Range, CriteriaRng As Range, CopyToRng As Range, NameMe As String, Optional FilterUnique As Boolean)
With CopyToRng
If WorksheetFunction.CountA(.Offset(1, 0).Resize(1, .Columns.Count)) <> 0 Then
CopyToRng.CurrentRegion.Offset(1, 0).ClearContents
End If
End With
FilterRng.AdvancedFilter _
Action:=xlFilterCopy, _
CriteriaRange:=CriteriaRng, _
CopyToRange:=CopyToRng, _
Unique:=FilterUnique
CopyToRng.CurrentRegion.Name = NameMe
End Sub
Private Sub CleanUpThisWorkbook()
Range("SalesExtract.Table").Offset(1).EntireRow.Delete
Range("SummaryFilter.Table").Offset(1).EntireRow.Delete
Range("DetailFilter.Table").Offset(1).EntireRow.Delete
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.

Runtime Error 91 Object Variable or With block variable not set with a Class

Im trying my first attempt at getting a recordset from a SQL server and passing the data from the recordset into a class. This is going to be part of a much bigger project by storing the recordsets into a dictionary that I can call on based on a user entered search criteria, which im sure I will get stuck on too. I used the Answer from this question as a guide to get me started, but since Im just now learning about using the Class Module; I am not sure why I am getting the Run-time error 91(identified in the code below). I have noticed that nothing seems to pass to the variables that I have designated within the clsCustInfo. Thank you for your assistance.
On quick side note: The On Error Resume Next is for the error that happens when the function tests to see which server the data is stored on.
Below is what is in my Class Module.
'CustomerInfo.cls
Private CustomerId As String
Private cName As String
Private cAddress1 As String
Private cAddress2 As String
Private cCity As String
Private cState As String
Private cZip As String * 5
Private cDoB As String
Private TableName As String
Private ErrNumber As Long
Public Property Get custID() As String
custID = CustomerId
End Property
Public Property Let custID(value As String)
custID = value
End Property
Public Property Get custName() As String
custName = cName
End Property
Public Property Let custName(value As String)
custName = value
End Property
Public Property Get custAddress1() As String
custAddress1 = cAddress1
End Property
Public Property Let custAddress1(value As String)
custAddress1 = value
End Property
Public Property Get custAddress2() As String
custAddress2 = cAddress2
End Property
Public Property Let custAddress2(value As String)
custAddress2 = value
End Property
Public Property Get custCity() As String
custCity = cCity
End Property
Public Property Let custCity(value As String)
custCity = value
End Property
Public Property Get custState() As String
custState = cState
End Property
Public Property Let custState(value As String)
custState = value
End Property
Public Property Get custZip() As String
custZip = cZip
End Property
Public Property Let custZip(value As String)
custZip = value
End Property
Public Property Get custDoB() As String
custDoB = cDoB
End Property
Public Property Let custDoB(value As String)
custDoB = value
End Property
Public Property Get tName() As String
tName = TableName
End Property
Public Property Let tName(value As String)
tName = value
End Property
Public Property Get eNumber() As Long
eNumber = ErrNumber
End Property
Public Property Let eNumber(value As Long)
eNumber = value
End Property
Below is in a Standard Module:
Option Explicit
Const CONNSTR = REDACTED FOR PUBLIC VIEWING
Const ConnectionError As Long = -2147467259
Sub CIFGrab()
Const bhschlp8 As String = "bhschlp8.jhadat842"
Const cncttp08 As String = "cncttp08.jhadat842"
Application.ScreenUpdating = False
'\\\\DATABASE OPERATIONS////
Dim tDBGrabRecord As clsCustInfo
tDBGrabRecord.tName = getCIFDBGrabTestRecord(cncttp08) <---ERROR 91 Happens on this line
If tDBGrabRecord.eNumber = ConnectionError Then tDBGrabRecord = getCIFDBGrabTestRecord(bhschlp8)
End Sub
Function getCIFDBGrabTestRecord(ByVal tName As String) As clsCustInfo
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQL As String
Dim tDBGrabRecord As clsCustInfo
On Error Resume Next
conn.Open CONNSTR
SQL = getCIFDBGrabSQL(tName)
rs.Open SQL, conn
tDBGrabRecord.eNumber = Err.Number
If Not (rs.BOF And rs.EOF) Then
rs.MoveFirst
If Not tDBGrabRecord.eNumber = ConnectionError Then
With tDBGrabRecord
.custID = Trim(rs.Fields("cifNum").value)
.custName = Trim(rs.Fields("custName").value)
.custAddress1 = Trim(rs.Fields("stAdd1").value)
.custAddress2 = Trim(rs.Fields("stAdd2").value)
.custCity = Trim(rs.Fields("City").value)
.custState = Trim(rs.Fields("State").value)
.custZip = Trim(rs.Fields("Zip").value)
.custDoB = Trim(rs.Fields("DoB").value)
.tName = tName
End With
rs.MoveNext
With tDBGrabRecord
Debug.Print "CIF:", .custID, "Name:", .custName, "Street 1:", .custAddress1, _
"Street 2:", .custAddress2, "City:", .custCity, "State:", .custState, _
"Zip:", .custZip, "DoB:", .custDoB
End With
End If
End If
rs.Close
conn.Close
getCIFDBGrabTestRecord = tDBGrabRecord
End Function
Function getCIFDBGrabSQL(ByVal TableName As String) As String
Dim SelectClause As String
Dim FromClause As String
Dim WhereClause As String
Dim JoinClause As String
SelectClause = "SELECT " & _
"cfcif# AS cifNum, cfna1 AS custName, " & _
"cfna2 AS stAdd1, cfna3 AS stAdd2, " & _
"cfcity AS City, cfstat AS State, " & _
"left(cfzip,5) AS Zip, " & _
"date(digits(decimal(cfdob7 + 0.090000, 7, 0))) AS DoB"
FromClause = "FROM " & TableName & ".cfmast cfmast"
WhereClause = "WHERE cfdead = '" & "N" & "'"
getCIFDBGrabSQL = SelectClause & vbNewLine & FromClause & vbNewLine & WhereClause
End Function
Something like this should work - I refactored a little bit.
Compiled but not tested.
Option Explicit
Const CONNSTR = "REDACTED FOR PUBLIC VIEWING"
Sub CIFGrab()
Const bhschlp8 As String = "bhschlp8.jhadat842"
Const cncttp08 As String = "cncttp08.jhadat842"
Dim tDBGrabRecord As clsCustInfo
'passing in all potential table names/sources in array
Set tDBGrabRecord = getCIFDBGrabTestRecord(Array(bhschlp8, cncttp08))
If tDBGrabRecord Is Nothing Then
MsgBox "Failed to get record", vbExclamation
Else
'work with tDBGrabRecord
End If
End Sub
Function getCIFDBGrabTestRecord(arrNames) As clsCustInfo
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQL As String, nm, okSql As Boolean
Dim tDBGrabRecord As clsCustInfo
conn.Open CONNSTR
'try each provided name: exit loop on successful query
For Each nm In arrNames
SQL = getCIFDBGrabSQL(CStr(nm))
On Error Resume Next
rs.Open SQL, conn 'try this name
If Err.Number = 0 Then okSql = True
On Error GoTo 0 'cancel on error resume next
If okSql Then
If Not rs.EOF Then
Set tDBGrabRecord = New clsCustInfo 'create an instance to populate
With tDBGrabRecord
.custID = Trim(rs.Fields("cifNum").value)
.custName = Trim(rs.Fields("custName").value)
.custAddress1 = Trim(rs.Fields("stAdd1").value)
.custAddress2 = Trim(rs.Fields("stAdd2").value)
.custCity = Trim(rs.Fields("City").value)
.custState = Trim(rs.Fields("State").value)
.custZip = Trim(rs.Fields("Zip").value)
.custDoB = Trim(rs.Fields("DoB").value)
.tName = CStr(nm)
Debug.Print "CIF:", .custID, "Name:", .custName, "Street 1:", .custAddress1, _
"Street 2:", .custAddress2, "City:", .custCity, "State:", .custState, _
"Zip:", .custZip, "DoB:", .custDoB
End With
'rs.MoveNext 'surely this is not needed here?
End If
Exit For 'done trying names
End If
Next nm
If rs.State = adStateOpen Then rs.Close
If conn.State = adStateOpen Then conn.Close
Set getCIFDBGrabTestRecord = tDBGrabRecord
End Function
Function getCIFDBGrabSQL(ByVal TableName As String) As String
Dim SelectClause As String
Dim FromClause As String
Dim WhereClause As String
Dim JoinClause As String
SelectClause = "SELECT " & _
"cfcif# AS cifNum, cfna1 AS custName, " & _
"cfna2 AS stAdd1, cfna3 AS stAdd2, " & _
"cfcity AS City, cfstat AS State, " & _
"left(cfzip,5) AS Zip, " & _
"date(digits(decimal(cfdob7 + 0.090000, 7, 0))) AS DoB"
FromClause = "FROM " & TableName & ".cfmast cfmast"
WhereClause = "WHERE cfdead = '" & "N" & "'"
getCIFDBGrabSQL = SelectClause & vbNewLine & FromClause & vbNewLine & WhereClause
End Function

Resources