I need short vba code to convert ms access table field to comma delimited string variable
T1.F to 'A','123','008','A'
A
123
008
A
The following will get your desired string in s :
Dim s as String, rs as Recordset
s = " Select [F] from [T1] "
Set rs = CurrentDb.OpenRecordset(s)
s = ""
While Not rs.EOF
s = s & "'" & rs(0) & "',"
rs.moveNext
Wend
s = Left(s,Len(s) - 1)
rs.close
Related
Using Excel VBA, I am trying to search through an SQLite table for names that appear in a filename.
In the code below, I have the NamesFound collection object to store the names.
When I loop through the recordset, I can add names to NamesFound and print them.
After the recordset is closed and variables are destroyed, when I print the number of items in the collection (NamesFound.count), I get a number that matches the number of matching names in the filename.
However, when I try to print any of the elements in the collection, I get the error message "Object is no longer valid".
Any idea why this happens?
Option Explicit
Sub SQLiteMatch()
Dim strSQL As String, fn As String
Dim NamesFound As Collection
Set NamesFound = New Collection
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rst As Object
Set rst = CreateObject("ADODB.Recordset")
fn = "C:\Clark Gable & Vivian Leigh in Gone With The Wind.mp4"
conn.Open "DRIVER=SQLite3 ODBC Driver;Database=C:\Path\To\cast&crew.db;"
strSQL = "SELECT id, person_name from People"
rst.Open strSQL, conn, 1, 1
With rst
.MoveFirst
Do Until .EOF
If InStr(1, fn, ![person_name]) > 0 Then
NamesFound.Add ![person_name]
Debug.Print "Names found: " & NamesFound.Count & " - " & _
NamesFound(NamesFound.Count) '<<< Works fine
End If
.MoveNext
Loop
End With
rst.Close
Set rst = Nothing
Set conn = Nothing
Debug.Print NamesFound(1) '<<< Error #3420: Object is no longer valid -
' same error for NamesFound.item(1) and NamesFound(1).Value
End Sub
Perhaps try:
...
'copy ![person_name] to a variable before adding to the Collection Dim personNameCopy As String With rst .MoveFirst Do Until .EOF
personNameCopy = ![person_name]
If InStr(1, fn, personNameCopy ) > 0 Then
NamesFound.Add personNameCopy
Debug.Print "Names found: " & NamesFound.Count & " - " & _
NamesFound(NamesFound.Count) '<<< Works fine
End If
.MoveNext Loop End With
...
The rst variable is set to Nothing before the last Debug.Print is executed and may have an effect on the ![person_name] reference added to the Collection.
How do I convert, in Classic ASP, this (example) comma separated Querystring
Illinois, Iowa, Wisconsin, Indiana, Kentucky,Missouri to
'Illinois', 'Iowa', 'Wisconsin', 'Indiana', 'Kentuck','Missouri'
I am using Dreamweaver and need this format to select records from a table which contain one of the states in the string Using IN clause.
If you need just the conversion here it is:
origstring = "Illinois, Iowa, Wisconsin, Indiana, Kentucky, Missouri"
convertedstring = "'" &replace(origstring, ", ","', '") &"'"
But let's say you (or anyone else) have a querystring with states:
strinclause = ""
arrstates = Split(Request.QueryString("states"), ",")
if(Ubound(arrstates) > 0) Then
for i=0 to Ubound(arrstates)
'VALIDATE/CLEAN YOUR ARRAY ITEMS AND BUILD YOUR STRING IN THIS WAY:
strinclause = strinclause & "'" &arrstates(i)& "',"
next
'NOW REMOVE LAST COMA
strinclause = Left(strinclause,Len(strinclause)-1)
end if
'HERE YOU CAN USE YOUR STRING THAT WILL BE IN THE FORMAT YOU ASKED
Jut spitballing, but you could do something like this:
<%
Dim qs : qs = Trim("" & Request.QueryString("states") ' e.g. "Illinois, Iowa, Wisconsin, Indiana, Kentucky, Missouri"
Dim cmd : Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = db.connection ' defined elsewhere
cmd.ActiveConnection.CursorLocation = adUseClient ' 3
cmd.CommandType = adCmdText ' 1
cmd.CommandTimeout = 90
dim inp : inp = Split(qs, ",") ' states
dim sql, i : ReDim sql (ubound(inp)) ' for sql
for i = 0 to ubound(inp)
sql(i) = "select ?" ' parameter in string
cmd.Parameters.Append cmd.CreateParameter("#p" & i, adVarChar, adParamInput, 100, inp(i)) ' actual typed parameter object
next
cmd.CommandText = "select id, stock from warehouse where state in (" & Join(sql, " union ") & ")"
Set rs = cmd.Execute
Do While Not rs.eof
response.write "<p>" & rs("id") & ": " & rs("stock") & "</p>"
rs.MoveNext
Loop
Set rs = Nothing
Set cmd = Nothing
%>
I'm using a DoCmd.TransferSpreadsheet to import data from Excel to Access.
Everything works fine except some Excel rows that are truncated because there are too much bytes for an Access single row (not field).
I noticed that every field in Access is created as a text(255) while my Excel rows are all no more than 100 characters.
I think that if I manage to import my Excel files creating fields with a default length of 100 chars, I will no longer get truncated data.
Is there a way to set the default text length for Access fields to a specific number?
UPDATE
Decreasing the default field text size in Access 2010 options seems to be ignored when running DoCmd.TransferSpreadsheet
To set the default text length for Access (2007), click the Office button > "Access Options button" > "Object Designers" (in the pane on the left), then under Table Design, enter 50 in the Default Text Field Size box and click OK.
I wrote my own import function, and it works:
' Import from an Excel with a default field length different from 255 (must be < 255)
Function importFromExcel(fileName As String, fieldLength as integer)
Dim my_xl_app As Object
Dim my_xl_worksheet As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Workbooks.Open(fileName)
Set s = my_xl_workbook.Worksheets(1)
Dim fieldsNumber As Integer
Dim recordNumber As Long
fieldsNumber = s.cells(1, s.Columns.Count).End(1).Column
recordNumber = s.cells(s.Rows.Count, 1).End(3).Row
tablename = "[" & Replace(GetFilenameFromPath(fileName), ".", "_") & "]"
On Error Resume Next
DoCmd.RunSQL "DROP TABLE " & tablename
On Error GoTo 0
' Creo tabella
sql = "CREATE TABLE " & tablename & " (F1 TEXT(" & fieldLength & ")) "
DoCmd.RunSQL sql
For i = 2 To fieldsNumber
sql = "ALTER TABLE " & tablename & " ADD COLUMN F" & i & " TEXT(" & fieldLength & ")"
DoCmd.RunSQL sql
Next
' Ora insert
For i = 1 To recordNumber
sql = "INSERT INTO " & tablename & " VALUES ("
For j = 1 To fieldsNumber
sql = sql & " '" & Replace(s.cells(i, j), "'", "''") & "',"
Next
sql = Mid(sql, 1, Len(sql) - 1)
sql = sql & ")"
Next
my_xl_workbook.Close SaveChanges:=False
Set my_xl_app = Nothing
End Function
I would like to connect to my Access tables using VBA. I want to be able to type in a purchase order number, and reference that value in a query to the Access table. I want to print the results of that query to my Excel worksheet. This is what I have so far.. any ideas?
Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Enter Purchase Order Number:")
Range("A1").Value = myValue
Call ADO_Conn(myValue)
End Sub
Sub ADO_Conn(myValue)
Dim conn As New Connection
Dim rstAnswer As New ADODB.Recordset
Dim connected As Boolean
Dim RootPath, DBPath As String
Dim tempString As String
connected = False
RootPath = "Z:\BSD Internship Program\FY14 Intern Files\John Jameson\Vouchers"
DBPath = RootPath & "Acquisition Support Datamart Build 9.11-03.accdb"
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= Z:\BSD Internship Program\FY14 Intern Files\John Jameson\Vouchers\Acquisition Support Datamart 9.1103.accdb;"
connected = True
rstAnswer.Open "SELECT VW_PUB_PURCHASE_ORDER.PO_NO FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
Do Until rstAnswer.EOF
tempString = CStr(rstAnswer!VW_PUB_PURCHASE_ORDER)
Application.ActiveWorkbook.Worksheets("Sheet1").Range("A5").Value = tempString
rstAnswer.MoveNext
Loop
rstAnswer.Close
conn.Close
connected = False
End Sub
A couple of things about your initial query:
rstAnswer.Open "SELECT VW_PUB_PURCHASE_ORDER.PO_NO FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
You are searching only for PO_NO in this query, so that is the only value that will return. If you want more than just that data (as I assume you might), then you want this:
rstAnswer.Open "SELECT * FROM VW_PUB_PURCHASE_ORDER " & _
"WHERE VW_PUB_PURCHASE_ORDER.PO_NO = ' " & myValue & " ';", conn, adOpenKeyset, adLockOptimistic
... where the asterisk means "all".
In addition, this bit concerns me:
' " & myValue & " '
You are adding leading and trailing blanks to your search term. This may or may not be what you want, but I assume that you do not want this. You probably want:
'" & myValue & "'
And if your PO_NO is a numeric value, you need to omit the apostrophes:
" & myValue & "
Lastly, I don't think you want to loop at all. The SELECT query will return all the results without requiring you to iterate rows. Maybe you should try getting rid of your "do" loop and using this instead:
Worksheets("Sheet1").Range("A5").CopyFromRecordset rstAnswer
Your query values will then be dropped into a dynamic range starting at the designated sheet & cell.
I didn't test the code so I might not have caught everything, but those jumped out at me.
Hope that helps!
Nate
I am writing an sql statement for an access database that will return a unique value regardless of the inputs. I am using this code however I am getting a type mismatch on the execute statement.
strSQL = "SELECT FilePath " _
& "FROM ToolFiles " _
& "WHERE Project_Num = '" & theSelectedProj & "'" _
& "AND Tool_Name = '" & theSelectedProjName & "'"
filePath = cn.Execute(strSQL)
Is there a way to return a string from an sql statement?
Thanks
The quick answer is No. The ADO Execute() method returns a recordset object which you will need to read into your string variable. Something like this should do it:
Dim rs As ADODB.Recordset
....
Set rs = cn.Execute(strSQL)
If Not (rs Is Nothing) Then
With rs
If Not (.BOF) And Not (.EOF) Then
strFilePath = Format$(.Fields(1).Value)
End If
End With
End If