Erase Data from a Field without a name acess vba - vba

I am trying to erase some data (values = 0) from a field in access, but without knowing the name, I only know the position of the field in the database (13Âșcolumn) . I thought it would be very simple, but after many tries I still can't manage to find a solution and I am starting to doubt if it's even possible.
So this is the code that I am using:
Sub Erasevalues0()
Dim strQValue As String
Dim i As Integer
Dim db As DAO.Database
Dim sql13 As String
Set db = CurrentDb
sql13 = db.TableDefs("TableName").Fields(13).Name
strQValue = "DELETE FROM TableName WHERE sql13=0;"
db.Execute strQValue
End Sub
I even tried something like:
strQValue = "DELETE FROM TableName WHERE Fields(13)=0;"
But nothing seems to work. Any suggestions?

I think you need to loop through the recordset. The following should work
Sub RemoveZeros()
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Table1", dbOpenDynaset)
rs.MoveFirst
With rs
Do Until .EOF
If .Fields(13) = 0 Then .Delete 'Delete row if column 13 = 0
.MoveNext 'Move to next record
Loop
End With
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub

Not sure if there is a direct way to use the index of a field. A workaround:
query = "SELECT * FROM TableName"
columnName = CurrentDb.OpenRecordset(query).Fields(13).Name
strQValue = "UPDATE TableName " & _
"SET " & columnName & "=''"

Related

I was wondering why am I getting this error?

(fake entries and file directories)
This is the error I got when trying to run a macro that takes values from a query and assigns them to a bookmark'd location on a word .docx
this is the line it fails on
Set rs = CurrentDb.OpenRecordset("Query1", dbOpenDynaset)
this is the query that the vba code is taking values from
SELECT Table1.ProjectNo, Table1.FirstName, Table1.LastName, Table1.Phone, Table1.ProjectName, Table1.EMail, Table1.Client
FROM Table1
WHERE (((Table1.LastName) Like "*" & [Forms]![Form3]![SearchBox] & "*"));
Private Sub Command9_Click()
Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim rs As DAO.Recordset
Set wApp = New Word.Application
Set wDoc = wApp.Documents.Open("C:\Documents\ECORtester.docx")
Set rs = CurrentDb.OpenRecordset("Query1", dbOpenDynaset)
If Not rs.EOF Then rs.MoveFirst
Do Until rs.EOF
wDoc.Bookmarks("Attention").Range.Text = Nz(rs![FirstName], "") & Nz(rs![LastName], "")
wDoc.Bookmarks("Client").Range.Text = Nz(rs![Client], "")
wDoc.Bookmarks("Email").Range.Text = Nz(rs![Email], "")
wDoc.Bookmarks("Phone").Range.Text = Nz(rs![Phone], "")
wDoc.Bookmarks("ProjectName").Range.Text = Nz(rs![ProjectName], "")
wDoc.Bookmarks("ProjectNumber").Range.Text = Nz(rs![ProjectNo], "")
wDoc.SaveAs2 "C:\Documents" & rs!ProjectNumber & "_ECORtester.docx"
rs.MoveNext
Loop
End Sub
Your WHERE clause has a parameter in it that isn't being set.
Define it as a querydef and create the recordset from that.
Dim qdf As QueryDef
Dim rs As Recordset
Set qdf = CurrentDb.QueryDefs("Query1")
qdf.Parameters("[Forms]![Form3]![SearchBox]") = [Forms]![Form3]![SearchBox]
Set rs = qdf.OpenRecordset
Recordset based on query object that has undefined/unset dynamic parameter won't work. Instead, base recordset on table and build SQL in VBA.
strSQL = "SELECT * FROM Table1 WHERE LastName Like "*" & [Forms]![Form3]![SearchBox] & "*"
Set rs = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
Using LIKE with wildcard could return multiple clients. If there are multiple people with same/similar last name, they could all be retrieved. If you want only one client, then use unique record ID as filter criteria. A combobox may be more useful than a free-form input textbox. With code, combobox can implement pattern matching and 'filter as you type' functionality but then selection is made from listed items and unique ID is available.

not able to edit record by passing text value through form access 2007

I have a first table called "BreedingTable" with primary key "ID" and "TransactionStatus" = "Active".
I have "Kidding form" data populated from the combo box to Text fields
Text2.value = "ID" from BreedingTable.
When I am done with all the process, I want to change TransactionStatus of Breeding table = Closed.
I am using the below code but it never works.
Note" if I give exact transaction id number it works fine,
but if I ask to find based on text2 it doesn't work.
My code is as follows:
Private Sub exitprograme3()
Me.Text2.SetFocus
Dim i As Integer
Dim db As Database
Dim rs As Recordset
Dim Trn As Integer
Set db = CurrentDb
Set rs = db.OpenRecordset("BreedingTable")
For i = 0 To rs.RecordCount - 1
Me.Text2.SetFocus
If rs.Fields("ID") = Me.Text2.Value Then
rs.Edit
rs.Fields("BreedingStatus") = "Closed"
rs.Update
End If
rs.MoveNext
Next i
rs.Close
Set rs = Nothing
db.Close
DoCmd.Close
End Sub
Please assist ...
If I type exact transaction id number in below if statement it works
If rs.Fields("ID") = "323" Then
this works fine.
But if I type like below it doesn't work
If rs.Fields("ID") = Me.Text2.Value Then
No loop is needed:
Private Sub exitprograme3()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("Select * From BreedingTable")
rs.FindFirst "[ID] = " & Me!Text2.Value & ""
' If ID is text, then quotes:
' rs.FindFirst "[ID] = '" & Me!Text2.Value & "'"
If Not rs.NoMatch Then
rs.Edit
rs.Fields("BreedingStatus").Value = "Closed"
rs.Update
End If
rs.Close
Set rs = Nothing
Set db = Nothing
DoCmd.Close
End Sub

SQL VBA: Selecting all tables with specific table name and field name

im working with access and VBA. As for now, I am trying to create a query with a SQL statement.
I have a bunch of tables, all of them are named "innen" at the end and they vary at the start. Each of these tables contain the column name "OP" (also other field names). Now my goal is to select all tables with the name containing '%innen' and the column name "OP". So far i tried this:
Sub Aktuell()
Dim strSQL As String
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As QueryDef
strSQL = "SELECT [*].OP FROM MSysObjects WHERE TABLE_NAME LIKE '%innen' ORDER BY MAX;"
db.Execute strSQL
Set qdf = CurrentDb.CreateQueryDef("NewQuery8", strSQL)
DoCmd.OpenQuery qdf.Name
End Sub
i tried this here aswell:
strSQL = "SELECT * " & _
"FROM INFORMATION_SCHEMA.TABLES " & _
"WHERE COLUMN_NAME = 'OP_Datum';"
But i keep getting errors.
Any ideas? does it even work with a sql statement via vba?
Here is a VBA solution for you.
Option Compare Database
Function GetFieldList(TableName As String) As String()
On Error GoTo Er
Dim Flds() As String
Dim fc As Long
Dim I As Long
'Initialize Dynamic Flds() Array
Flds = Split("")
fc = CurrentDb.TableDefs(TableName).Fields.Count - 1
If fc >= 0 Then
ReDim Preserve Flds(fc)
For I = 0 To fc
Flds(I) = CurrentDb.TableDefs(TableName).Fields(I).Name
Next I
End If
Done:
GetFieldList = Flds
Erase Flds
Exit Function
Er:
Resume Done
End Function
Sub flTest()
Dim I As Long
Dim Fields As Variant
Fields = GetFieldList("Customers")
If UBound(Fields) = -1 Then
MsgBox "Table Not Found, or Table has no fields", vbCritical + vbOKOnly
Exit Sub
End If
For I = LBound(Fields) To UBound(Fields)
Debug.Print """" & Fields(I) & """"
Next I
End Sub
I'll bet there is a way to so the same thing using nothing but SQL. Although, Access is a unique animal. You can do this using SQL Server. I'm not 100% sure Access can handle it. Well, why not try it and see for yourself.

How to use variable initiated in SQL query?

I made a query to get Max value of a certain column
sSQLmax = "SELECT MAX([tablename]!rowname) as MaxNum FROM [tablename]"
I want to use MaxNum value. I tried it in a Msgbox and gave me a blank value. I tried all these:
MsgBox "MaxNum" & MaxNum
MsgBox "MaxNum" & sSQLMAX.MaxNum
MsgBox "MaxNum" & sSQLMAX!MaxNum
More of the code
Dim db As DAO.Database, rst As DAO.Recordset
Set db = CurrentDb
Set rst = db.OpenRecordset(sSQLmax)
but none works, Im sure its simple but it escapes me
With your code you are only setting a variable to a string. You are not actually doing anything with it. This is probably more of what you are looking for:
Dim db As DAO.Database, rst As DAO.Recordset, sSQLmax As String
sSQLmax = "SELECT MAX([tablename].rowname) as MaxNum FROM [tablename]"
Set db = CurrentDb
Set rst = db.OpenRecordset(sSQLmax, dbOpenDynaset)
If (rst.RecordCount <> 0) Then
rst.MoveFirst
MsgBox "MaxNumber: " & rst.Fields("rowname")
End If
Try the DMax function
Dim result as String
result = DMax("[COLUMN NAME]", "[TABLE NAME]")

Export Query in VBA loop to select data based on String Value

I have a table called TEST, which I have code below that loops an export query based on unique values in the column Territory.
The code is supposed to export data to excel files based on the unique values in the column Territory. So each Territory value would have it's own file.
I am having trouble with setting up the sql query and how to use the string value to select the data:
Sub TEST()
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim v As String
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("Select Distinct Territory From TEST")
Do While Not rs1.EOF
v = rs1.Fields(0).Value
**DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, _
"WHAT SHOULD MY QUERY BE TO USE STRING v?", "C:\Users\me\Desktop\VBA_TEST\" v & ".xls", True**
rs1.MoveNext
Loop
rs1.Close
End Sub
Can someone guide me into how I may write the query and connect the string v so that it loops out reports?
Thank you!
I think you are required to use an existing query and not just your query as a string for the TransferSpreadsheet method. This means you will need a temporary query object to transfer your spreadsheet.
You can add a variable to query by joining it to the SQL string making sure that for text fields you include an ' on either side and leave it off for numeric fields.
Sub TEST()
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim v As String
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("Select Distinct Territory From TEST")
Dim strQry As String
Dim qdfTemp As DAO.QueryDef
Dim strQDF As String
strQDF = "_TempQuery_"
Do While Not rs1.EOF
v = rs1.Fields(0).Value
strQry = "SELECT * FROM TEST WHERE Territory = '" & v & "'"
Set qdfTemp = CurrentDb.CreateQueryDef(strQDF, strQry)
qdfTemp.Close
Set qdfTemp = Nothing
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, _
strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xls", True
CurrentDb.QueryDefs.Delete strQDF
rs1.MoveNext
Loop
rs1.Close
End Sub