Dynamically Create Collection/Array in VBA - vba

I'm struggling with this, I'm doing some stuff in Access with VBA and I need to dynamically create N collections/lists/arrays of records and add them to my dictionary.
//Some pseudo code
Dim dict as object
Set dict = CreateObject("Scripting.Dictionary")
for record in myRecordSetObject
if dict.exists(keyfromrecord)
dict(keyfromrecord) = array.add(record)
else
newarray = [record]
dict.add key:="keyfromrecord" item:=array
If it can't be done I might just do a string of primary keys and grow it as needed, then call string split.
Edit
So I have my records and I need to divide them into subgroups based on a few common fields that they may or may not share. If two records have the same pieces of information in these select fields they're in a subgroup. A subgroup may have 1 - N records.
Instead of getting all possible combinations and filtering my query I want to create a dictionary that defines it's key as a string generated from these fields. If a key exists then there's a member of that subgroup, if it doesn't it's a new subgroup.
The value was going to be an array of records.
Afterwards I was going to go through my dictionary and do stuff with these records.
Field1 Field2 Field3 Field4
Fruit Skinned Sliced Baked
Apples True True True
Bananas True True True
Oranges True False False
Using this example above subgroup would be when Field2,3 and 4 have the same value. (Apples, Bananas) and the other would be (Oranges)
I want a dictionary with Key being
dictionary{
"True-True-True": [Apples, Bananas],
"True-False-True": [Oranges]
}

Not sure if this is what you are after, but this puts a recordset of each combination in at each dictionary key.
Based on your table, it gives keys of
FALSE-FALSE-FALSE-,FALSE-FALSE-TRUE-,FALSE-TRUE-FALSE-,FALSE-TRUE-TRUE-,TRUE-FALSE-FALSE-,TRUE-FALSE-TRUE-,TRUE-TRUE-FALSE-,TRUE-TRUE-TRUE-
where ? dicOutput("TRUE-TRUE-TRUE-").recordcount returns 2 records
and GroupTable("0fruits")("TRUE-TRUE-TRUE-").recordcount the same 2
Hope this helps
Function GroupTable(strTableName As String) As Scripting.Dictionary
Dim strKey As String
Dim diccols As New Scripting.Dictionary
Dim dicOutput As Scripting.Dictionary
Dim dicTruth As Scripting.Dictionary
Dim rst As ADODB.Recordset
Dim rcols As ADODB.Recordset
Set rcols = New ADODB.Recordset
Set rcols = CurrentProject.Connection.OpenSchema(adSchemaColumns, Array(Empty, Empty, strTableName, Empty))
While Not rcols.EOF
If rcols.Fields("COLUMN_NAME").Value <> "Fruit" Then
diccols.Add CStr(diccols.Count), rcols.Fields("COLUMN_NAME").Value
End If
rcols.MoveNext
Wend
Set dicTruth = maketruthtable(2 ^ diccols.Count - 1, diccols.Count)
Set dicOutput = New Scripting.Dictionary
For l = 0 To dicTruth.Count - 1
strSQL = "select [fruit] from [" & strTableName & "] where " & Join(diccols.Items(), "&") & "='" & dicTruth.Items()(l) & "'"
Set rst = New ADODB.Recordset
rst.Open strSQL, CurrentProject.Connection, adOpenStatic
dicOutput.Add Replace(Replace(dicTruth.Items()(l), "-1", "TRUE-"), "0", "FALSE-"), rst
Next l
Set GroupTable = dicOutput
End Function
Function maketruthtable(intMax As Integer, intOptions As Integer) As Scripting.Dictionary
Dim d As New Scripting.Dictionary
Dim j As Integer
For j = 0 To intMax
d.Add CStr(j), Replace(Right(DecToBin(j), intOptions), "1", "-1")
Next j
Set maketruthtable = d
End Function
Public Function DecToBin(ByVal lngDec As Long) As String
Const MAXLEN = 5
Dim strBin As String
Dim n As Long
If lngDec < 0 Then
strBin = "1"
Else
strBin = "0"
End If
For n = MAXLEN To 0 Step -1
If lngDec And (2 ^ n) Then
strBin = strBin & "1"
Else
strBin = strBin & "0"
End If
Next
DecToBin = strBin
End Function
EDIT
Another solution would be to use SQL to do it, so if you have a table with just TRUE in 1 row and False in another, called tblLogicOptions for example, like so
Then you can use the following SQL on a table called 0Fruits
Using the following SQL
select LOGICTABLE.*,Data.Fruit FROM (select ((x1.a) & (x2.a) & (x3.a)) as Logic from tblLogicOptions as x1, tblLogicOptions as x2, tblLogicOptions as x3) AS LOGICTABLE
LEFT JOIN
(SELECT F1.Fruit, [skinned] & [sliced] & [baked] AS LogicCompare
FROM 0fruits as F1) AS DATA ON LOGICTABLE.Logic=DATA.LogicCompare
Which gives the results
Looping through this to build the dictionary, or even using the resultant recordset perhaps, would be easier I think.

You could use the Redim keyword to change the array size

Related

Unique Combinations in an array using VBA

I need a code that could give me a list of unique combinations from a set of elements in an array, something like this:
Say myArray contains [A B C]
So, the output must be:
A
B
C
A B
A C
B C
A B C
or
A B C
B C
A C
A B
A
B
C
either output is OK for me (Starts with 1 combination, followed by 2 combinations and ends with all combination OR vice versa).
The position of the letters are not critical and the order of letters within the same combination type is also not critical.
I'd found a suggestion by 'Dick Kusleika' in a thread: Creating a list of all possible unique combinations from an array (using VBA) but when I tried, it did not present me with the arrangement that I wanted.
I'd also found a suggestion by 'pgc01' in a thread: http://www.mrexcel.com/forum/excel-questions/435865-excel-visual-basic-applications-combinations-permutations.html and it gave me the arrangement that I wanted however, the combinations was not being populated in an array but it was being populated in excel cells instead, using looping for each combination.
So, I wanted the arrangement of combinations to be like what 'pgc01' suggested and being populated in an array as what 'Dick Kusleika' presented.
Anyone can help? Appreciate it.
Start from here:
Sub TestRoutine()
Dim inputt() As String, i As Long
Dim outputt As Variant
inputt = Split("A B C", " ")
outputt = Split(ListSubsets(inputt), vbCrLf)
For i = LBound(outputt) + 2 To UBound(outputt)
MsgBox i & vbTab & outputt(i)
Next i
End Sub
Function ListSubsets(Items As Variant) As String
Dim CodeVector() As Long
Dim i As Long
Dim lower As Long, upper As Long
Dim SubList As String
Dim NewSub As String
Dim done As Boolean
Dim OddStep As Boolean
OddStep = True
lower = LBound(Items)
upper = UBound(Items)
ReDim CodeVector(lower To upper) 'it starts all 0
Do Until done
'Add a new subset according to current contents
'of CodeVector
NewSub = ""
For i = lower To upper
If CodeVector(i) = 1 Then
If NewSub = "" Then
NewSub = Items(i)
Else
NewSub = NewSub & " " & Items(i)
End If
End If
Next i
If NewSub = "" Then NewSub = "{}" 'empty set
SubList = SubList & vbCrLf & NewSub
'now update code vector
If OddStep Then
'just flip first bit
CodeVector(lower) = 1 - CodeVector(lower)
Else
'first locate first 1
i = lower
Do While CodeVector(i) <> 1
i = i + 1
Loop
'done if i = upper:
If i = upper Then
done = True
Else
'if not done then flip the *next* bit:
i = i + 1
CodeVector(i) = 1 - CodeVector(i)
End If
End If
OddStep = Not OddStep 'toggles between even and odd steps
Loop
ListSubsets = SubList
End Function
Note we discard the first two elements of the output array.

VBA Excel concatenating two variable values to form a new variable

I am trying to write a code that reads in multiple entities, catorgorizes and sorts them. Each entity has a type (A, B, C, etc.) that should determine what sheet it gets put into and all of them get put into my "All" sheet. Each time I find an entity of any given type I'd also like to increment a variable specific to that type.
What I'd like to do if find the type and do two things:
Set the current sheet to that type.
Set the counter variable to that type.
Example:
Dim x As Integer, FindSlot As Integer
Dim CurrentSheet As String, CurrentPropertyNumb As String
Dim APropertyNumb As String, BPropertyNumb As String
Dim CPropertyNumb As String
For x = 1 to 2
If x = 1 Then
CurrentSheet = "All"
Else
CurrentSheet = Range("B" & FindSlot)
CurrentPropertyNumb = CurrentSheet & PropertyNumb
End If
Next x
In the else block, CurrentSheet will get set to "A", "B", "C" or whatever the type is. Then I'd like CurrentPropertyNumb to get set to "APropertyNumb" or "BPropertyNumb" etc. Obviously I could do this with several If statements but it would end up being 12 of them which I'd rather avoid plus I think this would be cool! :)
Is there any way to do this or am I being too lofty with my goals?
If you have a series of values which you'd like to index using a string value then a Dictionary is a good fit:
Dim x As Integer, FindSlot As Integer
Dim CurrentSheet As String, CurrentPropertyNumb As String
Dim PropNums as Object
Dim CPropertyNumb As String
Set PropNums = CreateObject("scripting.Dictionary")
For x = 1 to 2
If x = 1 Then
CurrentSheet = "All"
Else
CurrentSheet = Range("B" & FindSlot)
If Not PropNums.Exists(CurrentSheet) Then
PropNums.Add CurrentSheet, 1 '? what are the initial values here?
Else
PropNums(CurrentSheet) = PropNums(CurrentSheet) +1
End If
CurrentPropertyNumb = PropNums(CurrentSheet)
End If
Next x

Access 2010 Only returning first result Regular Expression result from MatchCollection

I am running a query using a regular expression function on a field where a row may contain one or more matches but I cannot get Access to return any matches except either the first one of the collection or the last one (appears random to me).
Sample Data:
tbl_1 (queried table)
row_1 abc1234567890 some text
row_2 abc1234567890 abc3459998887 some text
row_3 abc9991234567 abc8883456789 abc7778888664 some text
tbl_2 (currently returned results)
row_1 abc1234567890
row_2 abc1234567890
row_3 abc7778888664
tbl_2 (ideal returned results)
row_1 abc1234567890
row_2 abc1234567890
row_3 abc3459998887
row_4 abc9991234567
row_5 abc8883456789
row_6 abc7778888664
Here is my Access VBA code:
Public Function OrderMatch(field As String)
Dim regx As New RegExp
Dim foundMatches As MatchCollection
Dim foundMatch As match
regx.IgnoreCase = True
regx.Global = True
regx.Multiline = True
regx.Pattern = "\b[A-Za-z]{2,3}\d{10,12}\b"
Set foundMatches = regx.Execute(field)
If regx.Test(field) Then
For Each foundMatch In foundMatches
OrderMatch = foundMatch.Value
Next
End If
End Function
My SQL code:
SELECT OrderMatch([tbl_1]![Field1]) AS Order INTO tbl_2
FROM tbl_1
WHERE OrderMatch([tbl_1]![Field1])<>False;
I'm not sure if I have my regex pattern wrong, my VBA code wrong, or my SQL code wrong.
Seems you intend to split out multiple text matches from a field in tbl_1 and store each of those matches as a separate row in tbl_2. Doing that with an Access query is not easy. Consider a VBA procedure instead. Using your sample data in Access 2007, this procedure stores what you asked for in tbl_2 (in a text field named Order).
Public Sub ParseAndStoreOrders()
Dim rsSrc As DAO.Recordset
Dim rsDst As DAO.Recordset
Dim db As DAO.database
Dim regx As Object ' RegExp
Dim foundMatches As Object ' MatchCollection
Dim foundMatch As Object ' Match
Set regx = CreateObject("VBScript.RegExp")
regx.IgnoreCase = True
regx.Global = True
regx.Multiline = True
regx.pattern = "\b[a-z]{2,3}\d{10,12}\b"
Set db = CurrentDb
Set rsSrc = db.OpenRecordset("tbl_1", dbOpenSnapshot)
Set rsDst = db.OpenRecordset("tbl_2", dbOpenTable, dbAppendOnly)
With rsSrc
Do While Not .EOF
If regx.Test(!field1) Then
Set foundMatches = regx.Execute(!field1)
For Each foundMatch In foundMatches
rsDst.AddNew
rsDst!Order = foundMatch.value
rsDst.Update
Next
End If
.MoveNext
Loop
.Close
End With
Set rsSrc = Nothing
rsDst.Close
Set rsDst = Nothing
Set db = Nothing
Set foundMatch = Nothing
Set foundMatches = Nothing
Set regx = Nothing
End Sub
Paste the code into a standard code module. Then position the cursor within the body of the procedure and press F5 to run it.
This function is only returning one value because that's the way you have set it up with the logic. This will always return the last matching value.
For Each foundMatch In foundMatches
OrderMatch = foundMatch.Value
Next
Even though your function implicitly returns a Variant data type, it's not returning an array because you're not assigning values to an array. Assuming there are 2+ matches, the assignment statement OrderMatch = foundMatch.Value inside the loop will overwrite the first match with the second, the second with the third, etc.
Assuming you want to return an array of matching values:
Dim matchVals() as Variant
Dim m as Long
For Each foundMatch In foundMatches
matchValues(m) = foundMatch.Value
m = m + 1
ReDim Preserve matchValues(m)
Next
OrderMatch = matchValues
This loop
For Each foundMatch In foundMatches
OrderMatch = foundMatch.Value
Next
assigns all the results to the same variable OrderMatch in turn, which always replaces the old value of OrderMatch. Therefore the function will always return the last match.
If you want to return all the values, return an array for instance
Public Function OrderMatch(field As String) As String()
Dim results() As String
Dim i As Long
... get matches
ReDim results(0 To foundMatches.Count - 1) As String
If regx.test(field) Then
For i = 0 To foundMatches.Count - 1
results(i) = foundMatches(i).Value
Next
End If
OrderMatch = results
End Function
(I am currently working with Access XP, so I don't know whether the indexes go from 1 to Count or from 0 to Count-1.)
UPDATE
And always specify the return type of functions. This is more informative for people who want to use the function (including you if you have to resuse this function in 6 months) and prevents from supid coding errors. If really Variant is meant, specify ... As Variant so that your intention becomes clear.

DataTable: How to get item value with row name and column name? (VB)

I have a simple DataTable where one of the columns contains unique values. For example:
ColumnName1 ColumnName2
value1 35
value2 44
value3 10
Because I know that value 1, 2 and 3 will always be different one from another, I would like to get a value of this table only using ColumnName2 and one of the values of ColumnName1.
That would for example be:
searchedValue = DataTable.Rows("value3").Item("ColumnName2)
'result would be 10
I tried the following examples unsuccessfully:
with the DataTable.Select method: returns an array of rows, but I only need one
with the DataTable.Rows.IndexOf method: if I understood well, I need to provide the whole row contents for it to be found with this method.
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
With FirstOrDefault:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
'Create a class to hold the pair...
Public Class ColumnValue
Public ColumnName As String
Public ColumnValue As New Object
End Class
'Build the pair...
For Each row In [YourDataTable].Rows
For Each item As DataColumn In row.Table.Columns
Dim rowValue As New ColumnValue
rowValue.ColumnName = item.Caption
rowValue.ColumnValue = row.item(item.Ordinal)
RowValues.Add(rowValue)
rowValue = Nothing
Next
' Now you can grab the value by the column name...
Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select p.ColumnValue).FirstOrDefault
Next
For i = 0 To dt.Rows.Count - 1
ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)
Next
Try:
DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()
(This is C# code. Change this to VB equivalent)

How to List Field's Name in table in Access Using SQL

Can you please let me know if it is possible to list all fields name in a MS Access table?
I work in ms access far too much.
The only way I know of to do this, would be using vba, and defining for example a recordset, and looping through the fields.
Eg:
Sub ListFields()
dim rst as new adodb.recordset
rst.open "SELECT * FROM SomeTable", CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
' Note: adOpenForwardOnly and adLockReadOnly are the default values '
' for the CursorType and LockType arguments, so they are optional here '
' and are shown only for completeness '
dim ii as integer
dim ss as string
for ii = 0 to rst.fields.count - 1
ss = ss & "," & rst.fields(ii).name
next ii
Debug.Print ss
End Sub
The string variable ss will contain a comma-delimited list of all the column names in the table named "SomeTable".
With a little reformatting of the logic you should be able to insert this data into another table if you wanted to, then query it out.
Does this help?
This version is easy to run and will paste right into Access. Add this function to a module, run with F5, and copy the result from the inputbox:
Public Function FieldNames() As String
Dim sTable As String
Dim rs As DAO.Recordset
Dim n As Long
Dim sResult As String
sTable = InputBox("Name of table?")
If sTable = "" Then
Exit Function
End If
Set rs = CurrentDb.OpenRecordset(sTable)
With rs
For n = 0 To .Fields.Count - 1
sResult = sResult & .Fields(n).Name & vbCrLf
Next 'n
.Close
End With
Set rs = Nothing
InputBox "Result:" & vbCrLf & vbCrLf _
& "Copy this text (it looks jumbled, but it has one field on each line)", _
"FieldNames()", sResult
End Function
Alternative Output:
User user1003916 supplied an alternative to the InputBox to overcome the 1024 character limit (I have not tested this yet):
Sub CopyText(Text As String)
'VBA Macro using late binding to copy text to clipboard.
'By Justin Kay, 8/15/2014
Dim MSForms_DataObject As Object
Set MSForms_DataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
MSForms_DataObject.SetText Text
MSForms_DataObject.PutInClipboard
Set MSForms_DataObject = Nothing
End Sub
UPDATE: TO USE THIS SQL QUERY YOU MUST USE A TOOL SUCH AS DBEAVER.
ACCESS CLIENT WILL NOT ALLOW YOU TO QUERY IT'S HIDDEN STRUCTURES.
YIKES! IMO: I can't imagine wanting to dive into the dark underbelly of VBA
How to get Access Table Columns by SQL
SELECT * FROM information_schema.columns
WHERE TABLE_NAME="YOUR_TABLE_NAME"
AND
TABLE_SCHEMA="PUBLIC"
PS I noticed Access called my Schema "PUBLIC"
Above used an Access 2016 and was tested over ODBC and jdbc:ucanaccess and works like a charm.
Example output
You can simply use the Documenter tool. Go to Database Tools > Database Documenter, select the table and press OK.
This SQL works in Access 2016 for Queries, not Tables, but might be useful.
SELECT MSysObjects.Name AS QueryName,
IIf(IsNull([Name1]),
Right([Expression],Len([Expression])-InStr(1,[Expression],".")),[name1])
AS FieldName
FROM MSysQueries INNER JOIN MSysObjects
ON MSysQueries.ObjectId = MSysObjects.Id
WHERE MSysQueries.Attribute=6;
A quick and dirty method involves Excel. Do the following:
Open the table in Datasheet view.
Export to an Excel file, using the particular procedure for your Access version.
Open Excel file (if not already open).
Select and copy the first row containing the headers.
Add another sheet to the workbook (if none exist).
Click A1.
Paste Special > Transpose
The Fields will be pasted in a single column. To find out their Field Index number, in Cell B1 type "0", then series fill down to the last row of the field numbers.
In addition, you can sort the column alphabetically, especially for legacy flat files involving dozens of fields. This really saves a lot of time when I'm trying to convert a flatfile to a relational model.
There are already some good answers but I decided to add my own twist. Hopefully, they are self-explanatory.
Usage:
getFieldNames(TableName:="Table1",IncludeBrackets:=True,Delimiter:=vbNewLine,CopyToClipboard:=True)
getFieldNames(TableName:="Table1",IncludeBrackets:=True,CopyToClipboard:=True)
getFieldNames(TableName:="Table1",IncludeBrackets:=True)
getFieldNames(TableName:="Table1")
I use this to build an array of field names:
Chr(34) & getFieldNames(TableName:="Table1",IncludeBrackets:=False, Delimiter:= Chr(34) & "," & Chr(34)) & Chr(34)
Function getFieldNames(ByVal TableName As String, Optional ByVal IncludeBrackets As Boolean, Optional ByVal Delimiter As String = ", ", Optional ByVal CopyToClipboard As Boolean) As String
Dim rs As DAO.Recordset
On Error Resume Next
Set rs = CurrentDb.OpenRecordset(TableName)
On Error GoTo 0
If rs Is Nothing Then Exit Function
Dim results() As String
ReDim results(rs.Fields.Count - 1)
Dim n As Long
For n = 0 To rs.Fields.Count - 1
results(n) = rs.Fields(n).Name
Next
rs.Close
Dim result As String
If IncludeBrackets Then
result = "[" & Join(results, "]" & Delimiter & "[") & "]"
Else
result = Join(results, Delimiter)
End If
If CopyToClipboard Then
With CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.SetText result
.PutInClipboard
End With
End If
getFieldNames = result
End Function
This is not SQL, but this question is the top Google result for someone like me who just needs to list out the field names needed for a query to select since Access does not support "* except foo, bar" for getting 99% of a table.
Answer adapted from a social.msdn.com answer by Patrick Wood, Access MVP
https://social.msdn.microsoft.com/Forums/office/en-US/1fe5546b-db3f-4e17-9bf8-04f4dee233b7/how-to-list-all-the-field-names-in-a-specified-table?forum=accessdev
Change tablename to your name in the module. This Function should be at the global level:
Function ListTdfFields()
' NOT doing DIMs, since then you must enable/attach ADODB or DAO
' Dim db As ADO.Database
Set db = CurrentDb
tablename = "tblProductLicense" ' <=== YOUR TABLE NAME HERE
Set tdf = db.TableDefs(tablename)
For Each fld In tdf.Fields
Debug.Print tablename; ".["; fld.Name; "]," ;
' remove ending ; for 1 line per field
Next
Debug.Print ""
Set tdf = Nothing
Set db = Nothing
End Function
Then add a macro RunCode ListTdfFields() and run it. Output will be sent to the Immediate window of the VBA design view for the module.
I would like to share this VBA solution, which I did not write, only slightly modified (changed the tableName to use 'SourceTable'). Once it is run you can query the table it creates. It takes advantage of hidden system tables.
Sub GetField2Description()
'************************************************* *********
'Purpose: 1) Deletes and recreates a table (tblFields)
' 2) Queries table MSysObjects to return names of
' all tables in the database
' 3) Populates tblFields
'Coded by: raskew
'Inputs: From debug window:
' Call GetField2Description
'Output: See tblFields
'************************************************* *********
Dim db As DAO.Database, td As TableDef
Dim rs As Recordset, rs2 As Recordset
Dim Test As String, NameHold As String
Dim typehold As String, SizeHold As String
Dim fielddescription As String, tName As String
Dim n As Long, i As Long
Dim fld As Field, strSQL As String
n = 0
Set db = CurrentDb
' Trap for any errors.
On Error Resume Next
tName = "tblFields"
'Does table "tblFields" exist? If true, delete it;
DoCmd.SetWarnings False
DoCmd.DeleteObject acTable, "tblFields"
DoCmd.SetWarnings True
'End If
'Create new tblTable
db.Execute "CREATE TABLE tblFields(Object TEXT (55), FieldName TEXT (55), FieldType TEXT (20), FieldSize Long, FieldAttributes Long, FldDescription TEXT (20));"
strSQL = "SELECT MSysObjects.Name, MSysObjects.Type From MsysObjects WHERE"
strSQL = strSQL + "((MSysObjects.Type)=1)"
strSQL = strSQL + "ORDER BY MSysObjects.Name;"
Set rs = db.OpenRecordset(strSQL)
If Not rs.BOF Then
' Get number of records in recordset
rs.MoveLast
n = rs.RecordCount
rs.MoveFirst
End If
Set rs2 = db.OpenRecordset("tblFields")
For i = 0 To n - 1
fielddescription = " "
Set td = db.TableDefs(i)
'Skip over any MSys objects
If Left(rs!Name, 4) <> "MSys" And Left(rs!Name, 1) <> "~" Then
NameHold = rs!Name
On Error Resume Next
For Each fld In td.Fields
tableName = fld.SourceTable
fielddescription = fld.Name
typehold = FieldType(fld.Type)
SizeHold = fld.Size
rs2.AddNew
rs2!Object = tableName
rs2!FieldName = fielddescription
rs2!FieldType = typehold
rs2!FieldSize = SizeHold
rs2!FieldAttributes = fld.Attributes
rs2!FldDescription = fld.Properties("description")
rs2.Update
Next fld
Resume Next
End If
rs.MoveNext
Next i
rs.Close
rs2.Close
db.Close
End Sub
Function FieldType(intType As Integer) As String
Select Case intType
Case dbBoolean
FieldType = "dbBoolean" '1
Case dbByte
FieldType = "dbByte" '2
Case dbInteger
FieldType = "dbInteger" '3
Case dbLong
FieldType = "dbLong" '4
Case dbCurrency
FieldType = "dbCurrency" '5
Case dbSingle
FieldType = "dbSingle" '6
Case dbDouble
FieldType = "dbDouble" '7
Case dbDate
FieldType = "dbDate" '8
Case dbBinary
FieldType = "dbBinary" '9
Case dbText
FieldType = "dbText" '10
Case dbLongBinary
FieldType = "dbLongBinary" '11
Case dbMemo
FieldType = "dbMemo" '12
Case dbGUID
FieldType = "dbGUID" '15
End Select
End Function
Build query:
SELECT Table_Name.*
FROM Table_Name
WHERE False;
Export to Excel
You will have each field name in one row without any data. If you select the row and copy, you can paste special>transpose and have them all in a single column.
I came here searching for the same requirement and after refering to this thread, drafted below code for my requirement. The Field names form the source table will be added to an array and later the Field names are assigned to the second table. Just sharing it here, this migh help someone later..
Public Sub FieldName_Change()
Dim intNumberOfFields, intX As Integer
Dim txtTableName,txttmpTableName txtFieldName() As String
intNumberOfFields = GetFieldNames(txtTableName, txtFieldName())
For intX = 1 To intNumberOfFields
CurrentDb.TableDefs(txttmpTableName).Fields("F" & intX).Name = txtFieldName(intX)
Next intX
End Sub
Public Function GetFieldNames(ByVal txtTableName As String, ByRef txtFiledName() As String) As Integer
Dim rs As DAO.Recordset
Dim n As Long
Dim sResult As String
Set rs = CurrentDb.OpenRecordset(txtTableName)
ReDim txtFiledName(rs.Fields.Count)
With rs
For n = 0 To .Fields.Count - 1
txtFiledName(n + 1) = .Fields(n).Name
Next n
.Close
GetFieldNames = n
End With
Set rs = Nothing
End Function
Not sure why no-one came up with the following, I had the same issue and none of the above answers either worked or were suitable (No VB,thank you).
This is simple Java (error checking etc omitted)
String query="SELECT TOP 1 * FROM mytable";
ResultSet rs=connectionSQL.createStatement().executeQuery(query);
ResultSetMetaData rsm=rs.getMetaData();
int colcount=rsm.getColumnCount();
for(int f=1; f<=colcount; f++) {
String coltype=rsm.getColumnTypeName(f);
String colname=rsm.getColumnName(f);
.... (whatever)
}
So there's your columNames and the data types.
Works like a charm in MSACCESS
Seems like this task was easier in older days. Likely this answer is highly version-dependent. It works for me in a quick test against an Access 2007 DB:
select
Specs.SpecName AS TableName,
Columns.FieldName
from
MSysIMEXColumns Columns
inner join MSysIMEXSpecs Specs on Specs.SpecID = Columns.SpecID
order by
Specs.SpecName,
Columns.FieldName
Give this a go...
private void Button_OldDDLDump_Click(object sender, EventArgs e)
{
string _cnstr = "connectionstringhere";
OleDbConnection _cn = new OleDbConnection(_cnstr);
try
{
_cn.Open();
System.Data.DataTable _dt = null;
try
{
_dt = _cn.GetSchema("tables");
m_msghelper.AppendArray( DataTableHelper.DataTableToString(_dt) );
}
catch (Exception _ex)
{
System.Diagnostics.Debug.WriteLine(_ex.ToString());
}
finally
{
_dt.Dispose();
}
}
catch (Exception _ex)
{
System.Diagnostics.Debug.WriteLine(_ex.ToString());
}
finally
{
_cn.Close();
}
}
Helper method to dump the database structure to a string array here..
public static class DataTableHelper
{
public static string[] DataTableToString( System.Data.DataTable dt )
{
List<string> _retval = new List<string>();
foreach (System.Data.DataRow row in dt.Rows)
{
foreach (System.Data.DataColumn col in dt.Columns)
{
_retval.Add( string.Format("{0} = {1}", col.ColumnName, row[col]) );
}
_retval.Add( "============================");
}
return _retval.ToArray();
}
}
select column_name from information_schema.columns where table_name='table'