VBA Microsoft ActiveX Data Objects Library
The Microsoft ActiveX Data Objects library can be used to access various types of databases and execute queries using SQL. The ADODB.Stream class can be used to work with text streams.
Classes
Class | Description |
---|---|
Command | Defines a command to be executed against a database. |
Connection | Represents a connection to a database. |
Error | Represents an error generated by an operation on an ADO object. |
Errors | Collection containing Error objects. Errors are added to the Connection object's Errors collection property when the errors occur. |
Parameter | Represents a parameter of a parameterized query or stored procedure. |
Parameters | Collection containing all the Parameter objects of a Command object. |
Properties | Collection of Property objects for an ADO object. |
Property | Represents a property of an ADO object. |
Record | Represents a row of data. Can be a row from a Recordset. |
Recordset | Represents all records in a set of data. Can only point to one record at a time. |
Stream | Represents a stream of binary or text data. |
Enums and Consts
ADCPROP_ASYNCTHREADPRIORITY_ENUM
- adPriorityAboveNormal = 4
- adPriorityBelowNormal = 2
- adPriorityHighest = 5
- adPriorityLowest = 1
- adPriorityNormal = 3
ADCPROP_AUTORECALC_ENUM
- adRecalcAlways = 1
- adRecalcUpFront = 0
ADCPROP_UPDATECRITERIA_ENUM
- adCriteriaAllCols = 1
- adCriteriaKey = 0
- adCriteriaTimeStamp = 3
- adCriteriaUpdCols = 2
ADCPROP_UPDATERESYNC_ENUM
- adResyncAll = 15
- adResyncAutoIncrement = 1
- adResyncConflicts = 2
- adResyncInserts = 8
- adResyncNone = 0
- adResyncUpdates = 4
AffectEnum
- adAffectAllChapters = 4
- adAffectCurrent = 1
- adAffectGroup = 2
BookmarkEnum
- adBookmarkCurrent = 0
- adBookmarkFirst = 1
- adBookmarkLast = 2
CommandTypeEnum
- adCmdFile = 256
- adCmdStoredProc = 4
- adCmdTable = 2
- adCmdTableDirect = 512
- adCmdText = 1
- adCmdUnknown = 8
CompareEnum
- adCompareEqual = 1
- adCompareGreaterThan = 2
- adCompareLessThan = 0
- adCompareNotComparable = 4
- adCompareNotEqual = 3
ConnectModeEnum
- adModeRead = 1
- adModeReadWrite = 3
- adModeRecursive = 4194304
- adModeShareDenyNone = 16
- adModeShareDenyRead = 4
- adModeShareDenyWrite = 8
- adModeShareExclusive = 12
- adModeUnknown = 0
- adModeWrite = 2
ConnectOptionEnum
- adAsyncConnect = 16
ConnectPromptEnum
- adPromptAlways = 1
- adPromptComplete = 2
- adPromptCompleteRequired = 3
- adPromptNever = 4
CopyRecordOptionsEnum
- adCopyAllowEmulation = 4
- adCopyNonRecursive = 2
- adCopyOverWrite = 1
- adCopyUnspecified = -1
CursorLocationEnum
- adUseClient = 3
- adUseServer = 2
CursorOptionEnum
- adAddNew = 16778240
- adApproxPosition = 16384
- adBookmark = 8192
- adDelete = 16779264
- adFind = 524288
- adHoldRecords = 256
- adIndex = 8388608
- adMovePrevious = 512
- adNotify = 262144
- adResync = 131072
- adSeek = 4194304
- adUpdate = 16809984
- adUpdateBatch = 65536
CursorTypeEnum
- adOpenDynamic = 2
- adOpenForwardOnly = 0
- adOpenKeyset = 1
- adOpenStatic = 3
DataTypeEnum
- adArray = 8192
- adBigInt = 20
- adBinary = 128
- adBoolean = 11
- adBSTR = 8
- adChapter = 136
- adChar = 129
- adCurrency = 6
- adDate = 7
- adDBDate = 133
- adDBTime = 134
- adDBTimeStamp = 135
- adDecimal = 14
- adDouble = 5
- adEmpty = 0
- adError = 10
- adFileTime = 64
- adGUID = 72
- adIDispatch = 9
- adInteger = 3
- adIUnknown = 13
- adLongVarBinary = 205
- adLongVarChar = 201
- adLongVarWChar = 203
- adNumeric = 131
- adPropVariant = 138
- adSingle = 4
- adSmallInt = 2
- adTinyInt = 16
- adUnsignedBigInt = 21
- adUnsignedInt = 19
- adUnsignedSmallInt = 18
- adUnsignedTinyInt = 17
- adUserDefined = 132
- adVarBinary = 204
- adVarChar = 200
- adVariant = 12
- adVarNumeric = 139
- adVarWChar = 202
- adWChar = 130
EditModeEnum
- adEditAdd = 2
- adEditDelete = 4
- adEditInProgress = 1
- adEditNone = 0
ErrorValueEnum
- adErrBoundToCommand = 3707
- adErrCannotComplete = 3732
- adErrCantChangeConnection = 3748
- adErrCantChangeProvider = 3220
- adErrCantConvertvalue = 3724
- adErrCantCreate = 3725
- adErrCatalogNotSet = 3747
- adErrColumnNotOnThisRow = 3726
- adErrConnectionStringTooLong = 3754
- adErrDataConversion = 3421
- adErrDataOverflow = 3721
- adErrDelResOutOfScope = 3738
- adErrDenyNotSupported = 3750
- adErrDenyTypeNotSupported = 3751
- adErrFeatureNotAvailable = 3251
- adErrFieldsUpdateFailed = 3749
- adErrIllegalOperation = 3219
- adErrIntegrityViolation = 3719
- adErrInTransaction = 3246
- adErrInvalidArgument = 3001
- adErrInvalidConnection = 3709
- adErrInvalidParamInfo = 3708
- adErrInvalidTransaction = 3714
- adErrInvalidURL = 3729
- adErrItemNotFound = 3265
- adErrNoCurrentRecord = 3021
- adErrNotReentrant = 3710
- adErrObjectClosed = 3704
- adErrObjectInCollection = 3367
- adErrObjectNotSet = 3420
- adErrObjectOpen = 3705
- adErrOpeningFile = 3002
- adErrOperationCancelled = 3712
- adErrOutOfSpace = 3734
- adErrPermissionDenied = 3720
- adErrPropConflicting = 3742
- adErrPropInvalidColumn = 3739
- adErrPropInvalidOption = 3740
- adErrPropInvalidValue = 3741
- adErrPropNotAllSettable = 3743
- adErrPropNotSet = 3744
- adErrPropNotSettable = 3745
- adErrPropNotSupported = 3746
- adErrProviderFailed = 3000
- adErrProviderNotFound = 3706
- adErrProviderNotSpecified = 3753
- adErrReadFile = 3003
- adErrResourceExists = 3731
- adErrResourceLocked = 3730
- adErrResourceOutOfScope = 3735
- adErrSchemaViolation = 3722
- adErrSignMismatch = 3723
- adErrStillConnecting = 3713
- adErrStillExecuting = 3711
- adErrTreePermissionDenied = 3728
- adErrUnavailable = 3736
- adErrUnsafeOperation = 3716
- adErrURLDoesNotExist = 3727
- adErrURLNamedRowDoesNotExist = 3737
- adErrVolumeNotFound = 3733
- adErrWriteFile = 3004
- adwrnSecurityDialog = 3717
- adwrnSecurityDialogHeader = 3718
EventReasonEnum
- adRsnAddNew = 1
- adRsnClose = 9
- adRsnDelete = 2
- adRsnFirstChange = 11
- adRsnMove = 10
- adRsnMoveFirst = 12
- adRsnMoveLast = 15
- adRsnMoveNext = 13
- adRsnMovePrevious = 14
- adRsnRequery = 7
- adRsnResynch = 8
- adRsnUndoAddNew = 5
- adRsnUndoDelete = 6
- adRsnUndoUpdate = 4
- adRsnUpdate = 3
EventStatusEnum
- adStatusCancel = 4
- adStatusCantDeny = 3
- adStatusErrorsOccurred = 2
- adStatusOK = 1
- adStatusUnwantedEvent = 5
ExecuteOptionEnum
- adAsyncExecute = 16
- adAsyncFetch = 32
- adAsyncFetchNonBlocking = 64
- adExecuteNoRecords = 128
- adExecuteStream = 1024
FieldAttributeEnum
- adFldCacheDeferred = 4096
- adFldFixed = 16
- adFldIsChapter = 8192
- adFldIsCollection = 262144
- adFldIsDefaultStream = 131072
- adFldIsNullable = 32
- adFldIsRowURL = 65536
- adFldKeyColumn = 32768
- adFldLong = 128
- adFldMayBeNull = 64
- adFldMayDefer = 2
- adFldNegativeScale = 16384
- adFldRowID = 256
- adFldRowVersion = 512
- adFldUnknownUpdatable = 8
- adFldUpdatable = 4
FieldEnum
- adDefaultStream = -1
- adRecordURL = -2
FieldStatusEnum
- adFieldAlreadyExists = 26
- adFieldBadStatus = 12
- adFieldCannotComplete = 20
- adFieldCannotDeleteSource = 23
- adFieldCantConvertValue = 2
- adFieldCantCreate = 7
- adFieldDataOverflow = 6
- adFieldDefault = 13
- adFieldDoesNotExist = 16
- adFieldIgnore = 15
- adFieldIntegrityViolation = 10
- adFieldInvalidURL = 17
- adFieldIsNull = 3
- adFieldOK = 0
- adFieldOutOfSpace = 22
- adFieldPendingChange = 262144
- adFieldPendingDelete = 131072
- adFieldPendingInsert = 65536
- adFieldPendingUnknown = 524288
- adFieldPendingUnknownDelete = 1048576
- adFieldPermissionDenied = 9
- adFieldReadOnly = 24
- adFieldResourceExists = 19
- adFieldResourceLocked = 18
- adFieldResourceOutOfScope = 25
- adFieldSchemaViolation = 11
- adFieldSignMismatch = 5
- adFieldTruncated = 4
- adFieldUnavailable = 8
- adFieldVolumeNotFound = 21
FilterGroupEnum
- adFilterAffectedRecords = 2
- adFilterConflictingRecords = 5
- adFilterFetchedRecords = 3
- adFilterNone = 0
- adFilterPendingRecords = 1
GetRowsOptionEnum
- adGetRowsRest = -1
IsolationLevelEnum
- adXactBrowse = 256
- adXactChaos = 16
- adXactCursorStability = 4096
- adXactIsolated = 1048576
- adXactReadCommitted = 4096
- adXactReadUncommitted = 256
- adXactRepeatableRead = 65536
- adXactSerializable = 1048576
- adXactUnspecified = -1
LineSeparatorEnum
- adCR = 13
- adCRLF = -1
- adLF = 10
LockTypeEnum
- adLockBatchOptimistic = 4
- adLockOptimistic = 3
- adLockPessimistic = 2
- adLockReadOnly = 1
MarshalOptionsEnum
- adMarshalAll = 0
- adMarshalModifiedOnly = 1
MoveRecordOptionsEnum
- adMoveAllowEmulation = 4
- adMoveDontUpdateLinks = 2
- adMoveOverWrite = 1
- adMoveUnspecified = -1
ObjectStateEnum
- adStateClosed = 0
- adStateConnecting = 2
- adStateExecuting = 4
- adStateFetching = 8
- adStateOpen = 1
ParameterAttributesEnum
- adParamLong = 128
- adParamNullable = 64
- adParamSigned = 16
ParameterDirectionEnum
- adParamInput = 1
- adParamInputOutput = 3
- adParamOutput = 2
- adParamReturnValue = 4
- adParamUnknown = 0
PersistFormatEnum
- adPersistADTG = 0
- adPersistXML = 1
PositionEnum
- adPosBOF = -2
- adPosEOF = -3
- adPosUnknown = -1
PropertyAttributesEnum
- adPropNotSupported = 0
- adPropOptional = 2
- adPropRead = 512
- adPropRequired = 1
- adPropWrite = 1024
RecordCreateOptionsEnum
- adCreateCollection = 8192
- adCreateNonCollection = 0
- adCreateOverwrite = 67108864
- adCreateStructDoc = -2147483648
- adFailIfNotExists = -1
- adOpenIfExists = 33554432
RecordOpenOptionsEnum
- adDelayFetchFields = 32768
- adDelayFetchStream = 16384
- adOpenAsync = 4096
- adOpenExecuteCommand = 65536
- adOpenOutput = 8388608
- adOpenRecordUnspecified = -1
RecordStatusEnum
- adRecCanceled = 256
- adRecCantRelease = 1024
- adRecConcurrencyViolation = 2048
- adRecDBDeleted = 262144
- adRecDeleted = 4
- adRecIntegrityViolation = 4096
- adRecInvalid = 16
- adRecMaxChangesExceeded = 8192
- adRecModified = 2
- adRecMultipleChanges = 64
- adRecNew = 1
- adRecObjectOpen = 16384
- adRecOK = 0
- adRecOutOfMemory = 32768
- adRecPendingChanges = 128
- adRecPermissionDenied = 65536
- adRecSchemaViolation = 131072
- adRecUnmodified = 8
RecordTypeEnum
- adCollectionRecord = 1
- adSimpleRecord = 0
- adStructDoc = 2
ResyncEnum
- adResyncAllValues = 2
- adResyncUnderlyingValues = 1
SaveOptionsEnum
- adSaveCreateNotExist = 1
- adSaveCreateOverWrite = 2
SchemaEnum
- adSchemaActions = 41
- adSchemaAsserts = 0
- adSchemaCatalogs = 1
- adSchemaCharacterSets = 2
- adSchemaCheckConstraints = 5
- adSchemaCollations = 3
- adSchemaColumnPrivileges = 13
- adSchemaColumns = 4
- adSchemaColumnsDomainUsage = 11
- adSchemaCommands = 42
- adSchemaConstraintColumnUsage = 6
- adSchemaConstraintTableUsage = 7
- adSchemaCubes = 32
- adSchemaDBInfoKeywords = 30
- adSchemaDBInfoLiterals = 31
- adSchemaDimensions = 33
- adSchemaForeignKeys = 27
- adSchemaFunctions = 40
- adSchemaHierarchies = 34
- adSchemaIndexes = 12
- adSchemaKeyColumnUsage = 8
- adSchemaLevels = 35
- adSchemaMeasures = 36
- adSchemaMembers = 38
- adSchemaPrimaryKeys = 28
- adSchemaProcedureColumns = 29
- adSchemaProcedureParameters = 26
- adSchemaProcedures = 16
- adSchemaProperties = 37
- adSchemaProviderSpecific = -1
- adSchemaProviderTypes = 22
- adSchemaReferentialConstraints = 9
- adSchemaSchemata = 17
- adSchemaSets = 43
- adSchemaSQLLanguages = 18
- adSchemaStatistics = 19
- adSchemaTableConstraints = 10
- adSchemaTablePrivileges = 14
- adSchemaTables = 20
- adSchemaTranslations = 21
- adSchemaTrustees = 39
- adSchemaUsagePrivileges = 15
- adSchemaViewColumnUsage = 24
- adSchemaViews = 23
- adSchemaViewTableUsage = 25
SearchDirectionEnum
- adSearchBackward = -1
- adSearchForward = 1
SeekEnum
- adSeekAfter = 8
- adSeekAfterEQ = 4
- adSeekBefore = 32
- adSeekBeforeEQ = 16
- adSeekFirstEQ = 1
- adSeekLastEQ = 2
StreamOpenOptionsEnum
- adOpenStreamAsync = 1
- adOpenStreamFromRecord = 4
- adOpenStreamUnspecified = -1
StreamReadEnum
- adReadAll = -1
- adReadLine = -2
StreamTypeEnum
- adTypeBinary = 1
- adTypeText = 2
StreamWriteEnum
- adWriteChar = 0
- adWriteLine = 1
StringFormatEnum
- adClipString = 2
XactAttributeEnum
- adXactAbortRetaining = 262144
- adXactCommitRetaining = 131072
Use Cases
The ActiveX Data Objects library can be used to work with databases and streams.
Databases
The ADODB library can connect to various kinds of databases. SQL databases, Access databases, and Excel files are just some of the databases the ADODB library can work with. To connect to a particular type of data source use the appropriate connection string.
Public Sub Example()
'''Get data from .xlsx file
Dim SourcePath As String
SourcePath = Environ$("USERPROFILE") & "\Desktop\TestSource.xlsx"
Dim ConnectionString As String
ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourcePath & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Dim CommandText As String
CommandText = "SELECT * FROM [Sheet1$]"
Dim CN As ADODB.Connection
Set CN = CreateObject("ADODB.Connection")
Dim RS As ADODB.Recordset
CN.Open ConnectionString
Set RS = CN.Execute(CommandText)
Dim WS As Worksheet
Set WS = ThisWorkbook.Worksheets(1)
WS.Range("A1").CopyFromRecordset RS
RS.Close
CN.Close
Set RS = Nothing
Set CN = Nothing
End Sub
Streams
The ADODB Stream class can be used to work with streams of binary or text data. The Stream class can be used to create UTF-8 text files.
Public Sub WriteToTextFileUTF8(FilePath As String, TextContent As String)
Dim S As Object 'ADODB.Stream
Set S = CreateObject("ADODB.Stream")
Dim S1 As Object 'ADODB.Stream
Set S1 = CreateObject("ADODB.Stream")
With S
.Type = 2 'adTypeText
.Charset = "UTF-8"
.Open
.WriteText TextContent
.Position = 3
With S1
.Type = 1 'adTypeBinary
.Open
S.CopyTo S1
.SaveToFile FilePath, 2 'adSaveCreateOverWrite
.Close
End With
.Close
End With
End Sub
Public Function ReadFromTextFileUTF8(FilePath As String) As String
Dim ADOStream As Object
Dim OutputText As String
Set ADOStream = CreateObject("ADODB.Stream")
With ADOStream
.Charset = "UTF-8"
.Open
.LoadFromFile FilePath
OutputText = .ReadText()
End With
ADOStream.Close
Set ADOStream = Nothing
ReadFromTextFileUTF8 = OutputText
End Function