This is similar to this post storing code in a column and using it but has another twist to it
So, I have a column that has stuff like
"Ddddd " & color & " blah blah " & width & "kdndjnsnd"
So, id like to run a query that will populate color and width from the values of those columns in a table. So each row will get populated with a value from those columns on that record.
For example
Color Width Code
Black 5 "Ddddd '" & color & "' blah blah " & width & " kdndjnsnd"
Will produce the following for that record
Ddddd black blah blah 5 kdndjnsnd"
I know that doing this isn't recommended. I'm open to suggestions on how to accomplish this. I have a bunch of fields that need to be populated with dynamic values. Those values are burried inside blocks of text.
ETA here's a link to an excel file with an example of what i'm trying to do
excel file with an example
This is a very convoluted way to do a simple thing.
General rule: Data belongs in tables. Calculated fields / expressions belong in queries.
All your table should contain is the actual data columns:
ProductType Length Hardware Color Width
Everything else belongs into a query:
SELECT
"dddddd " & [Length] & " ft dddddd dog leash - dddddddd" AS ProductTitle,
"https://blah.com/ddddddd-" & [Color] & "-" & [Width] & "-" & [Hardware] & "-dog-leash-1.png" AS MainImg,
"https://blah.com/ddddddd-" & [Color] & "-" & [Width] & "-" & [Hardware] & "-ddddddd-1.png" AS Img1,
-- etc.
FROM Product_Data
Related
I'm attempting to pull data from my MS Access database via an Excel SQL statement. It does NOT give me any errors, however it also does not pull the data I'm searching for.
If items(u, 1) is text (ex. 308-203BL), then it works perfectly.
I've tried both comparing them as text and as numerical, but neither way find any matches when items(u, 1) is 19310.
This compares it as text...
LEFT(Item," & Len(items(u, 1)) & ") = '" & items(u, 1) & "'"
this compares it as numerical...
VAL(LEFT(Item," & Len(items(u, 1))) & ") = " & items(u, 1)
I have verified that there are records in the DB that match the given criteria.
items() is an array populated from a 1 column table on the sheet by items = Range("Items").Value.
Using these two SKU's as examples, the first working, the second not, the array would be as follows. .
SKU by SKU, they're fed into the SQL as below.
With the input in the example, the output I receive is an array populated only the sales for the second item. The order I put the SKU's in the table doesn't change that result. I have tested it with multiple SKU's, and no matter how many I use, it returns the proper information, with the exception of not returning any results for any numerical SKU's.
The field for Item in the DB is a short text, which is why I used '" & items(u, 1) & "'" to convert the SKU to text when I was trying to match it as text, and Val() to convert the field to a value when trying to match it as a number. Both gave me 0 record counts in the function, but did not give me a data type error.
Below is the portion of my code which determines the SQL string, and a bit afterwords which basically stuffs it into a UDF which pulls the info from the DB and puts it into an array for me. Aside from not finding a match when items(u,1) is numerical, it works perfectly.
DBString = "SELECT Invoice, Line, Inv_Date, Sales_Order, SOLine, SO_Date, CustID, Item, Part_Description, Ship_Qty, Price, Ext_Sales FROM `" & Year(tabledate) & "-" & Format(tabledate, "mm") & "` WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# AND LEFT(Item," & Len(items(u, 1)) & ") = '" & items(u, 1) & "'"
SalesHolder = PullFromDB(DBString, SGMDB)
I've also tried the below code instead, to force it to compare as a number instead of text, which also doesn't give me any errors, but doesn't find a match.
DBString = "SELECT Invoice, Line, Inv_Date, Sales_Order, SOLine, SO_Date, CustID, Item, Part_Description, Ship_Qty, Price, Ext_Sales FROM `" & Year(tabledate) & "-" & Format(tabledate, "mm") & "` WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# AND VAL(LEFT(Item," & Len(items(u, 1))) & ") = " & items(u, 1)
SalesHolder = PullFromDB(DBString, SGMDB)
Below is the UDF itself which pulls the info from the DB. It works quite nicely.
Function PullFromDB(DBStr As String, DBLoc As String) As Variant
Dim TheDB As Recordset, DBHolder() As Variant
Set TheDB = OpenDatabase(DBLoc).OpenRecordset(DBStr)
If TheDB.RecordCount = 0 Then GoTo theexit
TheDB.MoveLast
TheDB.MoveFirst
ReDim DBHolder(0 To TheDB.RecordCount, 1 To TheDB.Fields.Count) As Variant
For k = 1 To UBound(DBHolder, 2)
TheDB.MoveFirst
For j = 0 To UBound(DBHolder)
If j = 0 Then
DBHolder(j, k) = TheDB.Fields(k - 1).Name
Else
DBHolder(j, k) = TheDB.Fields(k - 1).Value
TheDB.MoveNext
End If
Next j
Next k
theexit:
TheDB.Close
Set TheDB = Nothing
PullFromDB = DBHolder
On Error GoTo -1
End Function
The expected result is to populate the array SalesHolder with the information that matches the criteria.
What am I missing? I'm going blind trying to find it.
Thank you all for your responses to this, it turns out I was completely hunting for the wrong problem. The code I posted was actually correct, the issue was with the format of Inv_Date field in the DB. I had mistakenly entered the last couple of months as text instead of date, so the WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# portion of my SQL didn't match anything.
I hadn't identified that this was the issue earlier due to the timing of the sales of the SKU's themselves, which was purely coincidence. When I expanded the dates range, I found that it did return results for the numerical SKU, but both numerical and text SKU's cut off two months ago.
Thank you again!
There is an SQL error 3134 syntax error when trying to insert these arrays into the data table in Microsoft access 2016. I am unsure if it is due to the fact that they are arrays or if it is due to their variable types
Currently I am using the Record set method to insert into my table, however due to .Update not accepting duplicates into the table I would like to use direct SQL injection to be able to add in the data.
Dim SCR_Link_Array(), SCR_Number_Array(), SCR_Unit_Array(), SCR_EquipTag_Array(), _
SCR_SCI_Array(), SCR_Title_Array(), SCR_EquipFail_Array(), SCR_Facility_Array() As String
Dim SCR_DiscoveryDate_Array(), SCR_FileDate_Array(), SCR_OccurenceDate_Array() As Date
Dim SCR_RowCount, row, record, field As Integer
'array definition happens here
For record = 0 To SCR_RowCount - 1
'This loop is for inserting lines into the DataBase table tblimportedSCRs
insertSQL = "INSERT INTO tblimportedSCRs(SCR #, Unit, System,Event Title,SCR Date,Date Occured,Discovery Date,Eq Fail,Facility) VALUES (" & SCR_Number_Array(record) & ", " & SCR_Unit_Array(record) & ", " & SCR_SCI_Array(record) & "," & SCR_EquipTag_Array(record) & "," & SCR_Title_Array(record) & "," & SCR_FileDate_Array(record) & "," & SCR_OccurenceDate_Array(record) & "," & SCR_DiscoveryDate_Array(record) & "," & SCR_EquipFail_Array(record) & "," & SCR_Facility_Array(record) & ")"
DoCmd.RunSQL insertSQL
Debug.Print (record)
Next record
I would like this to insert properly into the table however whenever I run the DoCmd.RunSQL insertSQL the code encounters runtime error 3134.
due to .Update not accepting duplicates into the table I would like
to use direct SQL
That won't make any difference.
If duplicates are not allowed, there is - by definition - no way to circumvent this.
Recently you guys helped me solve looping through a pivot table by inserting a dynamic formula next to a pivot table and auto filling down.
'formula
frml = "=if(" & myrange.Address(0, 0) & ">0.3%," & myrange2.Address(0, 0) & ","""")"
'where i want the formula to go
pt.ColumnRange.End(xlToRight).Offset(1, 0).End(xlToLeft).Offset(1, 1).formula = frml
ActiveSheet.range("P7:P36588").FillDown
I've tried updating this formula by adding
"=if(and("
and then also adding in another range. Problem is the additional ( never shows up. I've also tried just adding "(" as it's own part but then the next part (the 'where the formula goes) stops working which makes no sense to me.
Can someone help me convert this formula into an ifand statement and also explain why the 'where the formula should go' part all of the sudden stops working?
Edit:
In total, the new addition would look like this:
"if(and(" & myrange.address(0,0) & ">0.3%," & myrange3.address(0,0) & ">$100," & myrange2.address(0,0) & ","""")
to output this formula in the corresponding cell by the pivot table
=if(and(c3>.3%,d3>$100),a3,""
the problem right now is adding that and part to the formula which would be d3. If those 2 statements work, then it should bring out a3, if not it will return nothing.
A couple of notes:
#Jeeped already answered the reason to your error - you need to add closing bracket ) to your AND.
I like to use Chr(34) to write down " inside formula strings.
I like to avoid comparing the formats inside the cell, just the values. So instead of myrange.address(0,0) & ">0.3%" I like using myrange.address(0,0) & ">0.003".
Code
frml = "=IF(AND(" & myrange.Address(0, 0) & ">0.003," & myrange3.Address(0, 0) & ">100)," & myrange2.Address(0, 0) & "," & Chr(34) & Chr(34) & ")"
You aren't closing off the AND clause with a ).
'formula
frml = "=if(and(" & myrange.address(0,0) & ">0.3%, " & myrange3.address(0,0) & ">$100), " & myrange2.address(0,0) & ", text(,))
text(,) is a good substitute for """" in a quoted string formula.
I have a datatable containing several records. Each row of the datatable has a field that stores picture. When I loop through the datatable rows to insert them into a table of a database, every field of the row is saved correctly; but for every record, the picture in the first row of the datatable is saved. I traced the code and it does hit the lines that access and try to save the pictures in each row of the datatable. I am using VB.NET and the database is MS Access.
My code looks like this:
For Each dr As DataRow In dt.Rows
cmd.CommandText = "INSERT INTO Table1 (" & _
"[ID], " & _
"[Name], " & _
"[BDate], " & _
…….
"[TelNo], " & _
"[Photo]) " & _
" VALUES(" & _
dr("ID") & ", '" & _
dr("Name") & "', " & _
dr("BDate") & ", '" & _
…….
dr("TelNo") & "', " & _
img & ")"
cmd.Parameters.Add(img, OleDb.OleDbType.Binary).Value = dr("Photo")
cmd.ExecuteNonQuery()
Next
The code does exactly what you ask:
In your loop, all fields are varying following the values in your dataset row because you do this for each : dr(thefield)
except for the image because you just do this : img
It is thus always the same image.
You should have something like dr(image) (but I doubt it work as simply)
I find the answer myself. The problem is rather subtle. In OleDbCommands, parameters are not named. Parameters are represented by ? (the question mark). In the code snippet of my question, the variable img has the value of ?, which is assigned by a statement before the loop. The value of parameters MUST be provided in the order of their appearance. I my case, there is only one parameter and I provide a single parameter by the statement:
cmd.Parameters.Add(img, OleDb.OleDbType.Binary).Value = dr("Photo")
However, in each iteration of the loop, another parameter will be added. For the second record, the actual value of the parameter will be the second parameter , the third record will have its value at the third place, etc. Since in OleDbCommands values for parameters are identified by their order, and since there is only one parameter in my case, the picture provided first (i.e. that of the first record) is always used.
Hence the question boils down to ‘How can I provide a single parameter in each iteration?’ And the answer is to remove the parameter added by each iteration by including this precious statement:
cmd.Parameters.Clear()
as the last statement in the loop.
Sorry for the lengthy explanation.
I have a list box that is populated based on a previous filter (a text box). This means there is no predefined number of items in the listbox so using the index is impossible.
What I am looking for is a way of selecting the value of column(0), as there are 3 columns in my list box, of the selected line that is clicked.
Private Sub listSource_Click()
Dim strSource As String
strSource = "SELECT [Product Code],[Stock Level],[Description] FROM [products/stock] " & _
"WHERE Mid([Product Code],1,5) = " & Me.listSource.Column(0).Value & ";"
Me.listResult.RowSource = strSource
Me.listResult = vbNullString
End Sub
What I think I need is just the small piece of code that is supposed to be where "Me.listSource.Column(0).Value" is.
Thanks in advance,
Bob P
I reckon you want:
strSource = "SELECT [Product Code],[Stock Level],[Description] " & _
"FROM [products/stock] " & _
"WHERE Mid([Product Code],1,5) = '" & Me.listSource & "';"
Note the single quotes before and after Me.listSource.
Me.listresult gives the bound column
you then have to append .Column(0),.Column(1) ... for other columns.
to find out which one of the list you need to be looking at, .ItemsSelected.Count will tell you how many are selected (1 for a simple list box), and .ItemsSelected(0) for the index to the first item selected, so, the complete line for the first column of the first selected line would be:
Me.listSource.ItemData(Me.ListSource.ItemsSelected(0))
You should be able to use Me.ListSource.Column(0) to get the value of the first column of the selected row.
Also see: Retrieve column values of the selected row of a multicolumn Access listbox