Parsing Listbox results and updating values - parsing

The included code pulls parameters from a form and executes a stored procedure. The result is captured via a list box object and displayed on the form. How can I parse the result from the stored procedure, modify values, and then submit it back so the list box shows the updates?
My stored procedure returns a list of user accounts and their status (1,0). What I want to do is update the status from 1,0 to true,false so that when the results are shown in the form, the listbox shows true and false as opposed to 1,0.
Dim paramAcctNo As String
Dim paramProfileId As String
Dim query1 As String
Dim query2 As String
'Populating the form parameters
paramAcctNo = [Forms]![frm_userlookup]![lst_searchresults]
paramProfileId = [Forms]![frm_userlookup]![tb_hidden]
'Executing SP
query1 = "EXEC dbo.sp_ADCON_userDetailView '" & paramAcctNo & "','" & paramProfileId & "'"
'assigning results to listbox to display in form
Me.listbox1.RowSource = query1

If you are allowed to change the actual values in the query1 table after your stored procedure has run, you can run two simple UPDATE queries to change the 1s to True and the 0s to False.
UPDATE query1 SET [field name that contains the 1] = "True"
WHERE ([field name that contains the 1]="1")
UPDATE query1 SET [field name that contains the 0] = "False"
WHERE ([field name that contains the 0]="0")
A problem that you might run into is with a Type mismatch error. If the field containing the 0s and 1s is numeric, you won't be able to update it to a string value.

Related

How to take a named path string stored in Excel's name manager and open a file using it. The stored string contains the entire file string

The first routine grabs the filename string as the user locates a file which was exported from Quickbooks
The second routine writes that name into the name manager as a string under the name
"PathToEmployeeWithholding"
The third routine attempts to open the file using the name stored in the name manager
I have verified in the name manager that the name and correct path string is there, but I have not been successful in using that name to retrieve the file for reading.
The current code returns a 1004 error, but debug.print does give the correct path, pasting the string in the windows run box opens the spreadsheet, and so does a static statement with the path.
Thanks in advance for your help
lang-VB
'HouseKeepingCODE Module
Sub GetPath()
'This sub gets the path to a File defined by the user within the routine
'It then calls another sub that applies that path to a name in the worksheet.
' Before calling this routine, The name should first be searched for, and then verified, then opportunity given to change the name.
Dim MyPath As String 'String to hold the path to an excel spreadsheet exported from quickbooks
Dim NameToChange As String 'String that holds the name manager name to store the path under
Dim NameComment As String 'Comment to identify the name in the name manager
NameToChange = "PathToEmployeeWithholding"
NameComment = "This Name contains the Path to the 'Employee Withholding' worksheet exported from quickbooks using VBA"
With Application.FileDialog(msoFileDialogFilePicker)
If .Show <> 0 Then
MyPath = .SelectedItems(1)
End If
End With
'Debug.Print PathToWithholding
'This routine should be modified
'It should simply get a path to a file,
'And return that path to the calling subroutine
'The calling subroutine should then add comment and call the changevalueofname subroutine
Call ChangeValueOfName(NameToChange, MyPath, NameComment) 'this routine stores the retrieved text string in the name manager
End Sub
Sub ChangeValueOfName(NameToChange As String, NewNameValue As String, Comment As String)
'
' ChangeValueOfNameMagagerName Macro
' Changes the Value of a defined name in the Name Manager
'This should be used to change the name.
'
'Once the file is selected data needs to be imported to an array, and the
'Employee name values need to be checked against the worksheets in the workbook and against the recap sheet
'If changes are needed, it needs to write them into the workbook, including changing recap sheet and adding
'worksheets for any new employees
'
'
'
'
With ActiveWorkbook.Names(NameToChange)
.Name = NameToChange
.RefersTo = NewNameValue
.Comment = Comment
End With
End Sub
'****problem subroutine below***
Sub UpdateEmployeewithholding()
'This sub will clean employee withholding as it is exported from quickbooks and then read the file into this workbook
'The path is already stored in the names manager
'This routine needs to integrate changevalueofname and getpath. They should update before executing the balance of this routine
Dim MyWorkBook As Workbook
Dim MyPath As Variant 'Contains path to employee withholding spreadsheet as exported from quickbooks. This sheet is to be modified for reading, but not saved
Dim MyRange As Range 'Contains a defined range after setting it so
Dim whichrow As Variant 'Marks the starting point for routines that find and delete blanks as well as those that define range values and scan them into an array
Dim Direction As Variant 'Defines whether we are progressing over "Rows" or "Columns"
Dim ArrayWidth As Range 'Holds the top row addresses of the array
Dim ArrayHeight As Range 'Holds the left column addresses of the array
Dim MyArray As Variant 'Holds the array to transfer to this spreadsheet
Dim Width As Long 'Holds the array width to prevent loosing it when the original spreadsheet closes
Dim Height As Long 'Holds the array height to prevent loosing it when the original spreadsheet closes
whichrow = 1 'We are starting in cell A! or R1C1
Direction = "Rows"
'******************************************************************************************************
'***INSERT Code that will read the string value stored in the name manager Name "PathToEmployeeWithholding" into the variable "MyPath"
' and eliminate the hard coded path from the routine
' STILL MISSING
'*****************************************************************************************************
'Setting MyPath to the fixed path to employee withholding until we can get the routine to 'open the workbook from a varialbe
'stored in the name manager
MyPath = ThisWorkbook.Names("PathToEmployeeWithholding")
'ActiveWorkbook.Names (PathToEmployeeWithholding)
Debug.Print MyPath 'This works
Set MyWorkBook = Workbooks.Open(MyPath) '***Problem line returns 1004 stored-path could
'not be found
Debug.Print ActiveWorkbook.Name
'**** The immediate statement below worked ***
debug.Print thisworkbook.Names("PathToEmployeeWithholding")="D:\redacted\Employee Withholding .xlsx"
'***Code below to extract data from workbook opened above
The problem was in the fact that pulling the name back from name manager always added an = sign plus open and close quotes for delimiters. .eg
="string\text"
The solution was to strip the delimiters using the mid function
Sub UpdateEmployeewithholding()
'This sub will clean employee withholding as it is exported from quickbooks and then read the file into this workbook
'The path is already stored in the names manager
'This routine needs to integrate changevalueofname and getpath. They should update before executing the balance of this routine
Dim MyWorkBook As Workbook
Dim MyPath As String 'Contains path to employee withholding spreadsheet as exported from quickbooks. This sheet is to be modified for reading, but not saved
Dim MyRange As Range 'Contains a defined range after setting it so
Dim whichrow As Variant 'Marks the starting point for routines that find and delete blanks as well as those that define range values and scan them into an array
Dim Direction As Variant 'Defines whether we are progressing over "Rows" or "Columns"
Dim ArrayWidth As Range 'Holds the top row addresses of the array
Dim ArrayHeight As Range 'Holds the left column addresses of the array
Dim MyArray As Variant 'Holds the array to transfer to this spreadsheet
Dim Width As Long 'Holds the array width to prevent loosing it when the original spreadsheet closes
Dim Height As Long 'Holds the array height to prevent loosing it when the original spreadsheet closes
Dim StrLength As Long
whichrow = 1 'We are starting in cell A! or R1C1
Direction = "Rows"
MyPath = ThisWorkbook.Names("PathToEmployeeWithholding") 'get string from name manager
Debug.Print MyPath 'As stored in name manager the name always returns and = sign plus open and close quotes
StrLength = Len(MyPath) 'In order to get the workbook to open programatically these must be stripped
MyPath = Mid(MyPath, 3, StrLength - 3) 'The mid statement strips these delimiters off, leaving just the text
Debug.Print MyPath
Set MyWorkBook = Workbooks.Open(MyPath)
Debug.Print ActiveWorkbook.Name
'Stuff below gets data from opened workbook

How to sort on hidden or data-attribute value in textSorter

I have a "name" column in a table that contains a persons full name (ie. first+last name). The objective is to sort the column based on the person's last name first, then first name. My initial naive approach for the textsorter function was
function (a, b){
const aSplit = a.split(' ');
const bSplit = b.split(' ');
const aReverse = aSplit[1] + aSplit[0];
const bReverse = bSplit[1] + bSplit[0];
return aReverse.localeCompare(bReverse);
}
Unfortunately, some of the names I have to sort have extraneous spaces in them, potentially in either the first name or last name field. So I have to support this in my sorting.
I am currently only using the combined first+last name string for display and sorting but I have access to the seperate name strings as well as a preformatted lastname, firstname version. I'd like to attach either of these to the <th> tags as a data attribute or something like that and sort using that instead of the actual value but I'm not sure how to go about accessing those attributes from within the textsorter function.
Maybe try this - when you build the table HTML, add the last name + first name into a data-text attribute of the cell. Tablesorter will automatically use that attribute over the actual text within the cell. See textAttribute option to allow changing that attribute name.

Passing parameters from Logic app to CosmosDB stored procedure with parameterized sql query

I am trying to call a stored procedure in CosmosDB from Logic App with some parameters to be able to retrive the number of documents that meet the query requirements.
Example of query I want to do:
SELECT * FROM c where c.Time_Stamp BETWEEN time1 AND time2
I have tried to test my stored procedure in Data Explorer. this what I was doing.
// SAMPLE STORED PROCEDURE
function sample(input) {
var context = getContext();
var collection = getContext().getCollection();
var response = context.getResponse();
//var inputtf = JSON.parse(input).id;
var filterQuery = "SELECT * FROM c where c.id = "+ input ;
console.log(filterQuery);
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
filterQuery,
function (err, feed, options) {
if (err) throw err;
response.setBody(JSON.stringify(feed));
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
As an input I was giving:
I get this an a result :
SELECT * FROM c where c.id = 220
So I can see that my query is able to get parameters in it.
The thing is I get no results for that query (Result is "[]")
This is my document I am trying to query:
This would be the kind of payload I would sent to the stored procedure to begin with. Next step would be to add a start time and end time parameters in UTC.
As an end goal, I would like to get in Logic App, in the output, a count of how many documents were meeting the query requirement.
If I'm not wrong, the partition key parameter for the execute store procedure activity should be sent as string. So, you need to add quotes between your partition key value.
In your case: "42976" instead of 42976
The stored procedures need a valid partition key value to be executed and to response the query. You can see a note in the top of this page from Microsoft documentation: https://learn.microsoft.com/en-us/azure/cosmos-db/sql/how-to-write-stored-procedures-triggers-udfs?tabs=javascript

UniDac on PostgreSQL: no value on serial (autoincrement) field after insert

In my application user have ability to add some records to database.
I'am using UniDac 4.6.12 components.
For autoincrement field, we are using serial PostgreSQL type and I don't touch value of this field in my application.
But, after Post of record, the value of field is 0.
Also, I get 0 from:
Q := dmMain.aqrParts.LastInsertId;
If I refresh the dataset, record will appear with filled serial field value, but it is not comfortable way for user, because table have a lot of records, and to fetch some records to work, for user necessary to set a lot of filters.
I using this kind of properties of dataset:
object aqrParts: TUniQuery
Connection = psqlConnection
SQL.Strings = (
'SELECT * FROM parts.spareparts'
'LIMIT 200')
SpecificOptions.Strings = (
'PostgreSQL.UnpreparedExecute=True')
BeforePost = aqrPartsBeforePost
AfterPost = aqrPartsAfterPost
Left = 32
Top = 72
object aqrPartsId: TIntegerField
AutoGenerateValue = arAutoInc
FieldName = 'id'
Visible = False
end
...
Is it possible to solve this?
When you create a field with the serial type, PostgreSQL server automatically creates a sequence, and values from this sequence will be used as default for this field
To fill Id field automatically you can use two ways:
1) Set
aqrParts.Options.DefaultValues := True.
In this case default value for the Id field will be set to "nextval(''parts.spareparts_seq''::regclass)" and the Id field will be filled automatically.
2) Set
aqrParts.SpecificOptions.Values['KeySequence'] := 'spareparts_seq';
aqrParts.SpecificOptions.Values['SequenceMode'] := 'smInsert';
In this case field Id will be filled from this sequence.
This page on PostgreSQL Sequence Manipulation Functions suggests you may be able to use the nextval function to get the next value of the identity/autoincrement/sequence field before you insert. So you could get this guaranteed unique value first, then display it on the form before the user begins entering any other field values, and finally explicitly include this value in the insert statement.
Quote from the documentation on nextval function
Advance the sequence object to its next value and return that value. This is done atomically: even if multiple sessions execute nextval concurrently, each will safely receive a distinct sequence value.

How to get data out of a recordset in excel?

I have the following code:
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim AppPath As String
Set cn = CreateObject("ADODB.Connection")
AppPath = Application.ActiveWorkbook.Path
Set rs = CreateObject("ADODB.RecordSet")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & AppPath & "\Masterlist_Current_copy.accdb;"
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"
cn.Open strConnection
Set rs = cn.Execute(strSql)
'Need Code here to get Info out of recordset
I am trying to get information out of the recordset that has the query result being dumped into it. I'm trying to figure out how to query the recordset and get the number of rows with a specific value in the "Neptune Number" field. I will then insert the correct number of rows into the worksheet I'm modifying. After that I need to get the data for that value and insert it into the worksheet.
Note: I don't care if recordset, datatable or anything else is used I simply need to be able to do what I described above. Please show code.
The easiest way to get where you I think you are asking to go is to modify your SQL statement changing
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components];"
to
strSql = "SELECT [Neptune Number],[Description],[Manufacturer],[Manufacturer P/N] FROM [All Components] WHERE [Neptune Number] = 'Specific Value' ;"
This will force the sql query to only return the records you need. the .find method can be used for filtering the recordset, but i have avoided using it in this instance as it is cleaner to just ask the db for only the information that you want.
to process the recordset you can use the following
with rs
'will skip further processing if no records returned
if not (.bof and .eof) then
'assuming you do not need the headers
'loop through the recordset
do while not .eof
for i = 0 to .fields.count -1
'assuming the active sheet is where you want the data
cells(row, i + colOffset) = .fields(i).value
next
Rows(Row & ":" & Row).Insert
.movenext
loop
end if
end with
Where row is the starting point of your data and colOffset is the starting column of your data. Note that this code does not do things in the exact order you specified in your question (I am inserting rows as needed instead of calcualting the number of records up front.)
I have avoided using .recordcount because I find depending on the database used it will not return a correct record count.

Resources