Ampscript BuildRowsetFromString() fails on single item - exacttarget

I've been tasked with an ExactTarget task, which uses Ampscript. Trying to learn on the go here. See code snippet below:
%%[
Var #testString, #testOutput
Set #testString = Qwerty
Set #testOutput = BuildRowsetFromString(#testString,"~")
]%%
TestOutput:%%= v(#testOutput) =%%
The code works if the testString contains a ~, but when there is no ~ character in the string, the ouput is blank. Is this correct by design? Do I need to add a conditional to check for the presence of the ~ character?

That's the expected behavior. The BuildRowsetFromString() function alone isn't going to return any value when displayed, you're going to need to use Row() and Field() in order to pull the value out.
Using your example:
%%[
Var #testString, #testOutput
Set #testString = "Qwerty"
Set #testOutput = BuildRowsetFromString(#testString,"~")
]%%
RowCount: %%=RowCount(#testOutput)=%%
TestOutput: %%=v(#testOutput)=%%
The RowCount() function returns a value of 1, essentially saying it knows there's at least one 'row' in there. To display that one value, you'll need to wrap that value with Field() and Row():
TestOutput: %%=Field(Row(#testOutput,1),1)=%%
If you want to display other values in the string, say you were passing "Qwerty~Second~Third", you'll need to either change the number at the Row() function or perform a loop.
References
Using Loops
BuildRowsetFromString() Function

Related

App Script - Google Sheets - basics of working with strings

First time posting here. I'm an experienced coding, but it's been a long time since I've done any, and I'm starting back up with App Script, a new language for me. I'm trying to do some basic stuff with text found within cells in a Google sheets. I've gotten it to work well enough, but I think my code can be simplified and improved if I learn a little bit more about working with text strings in App Script.
This is a very simplified version of my function. My real function finds the page numbers given in a citation in one cell, and puts just those page numbers in another cell. For the purposes of this question, I've simplified it to retrieve the text from the current cell, remove the first blank space in the text, count the numbers at the beginning of the text, and then write just those numbers into the current cell. It does what it is supposed to do, and what I need it to do, but I have so many questions! Thank you!!
function myFunction() {
var spreadsheet = SpreadsheetApp.getActive(); var
currentCell = spreadsheet.getCurrentCell().activate();
var style = SpreadsheetApp.newTextStyle().setForegroundColor('#000000').build();
var textString = currentCell.getRichTextValue().getText();
var count = 0;
var char = textString.substring(count,count+1);
textString = textString.replace(" ","");
while(char<10)
{
count = count+1;
char = textString.substring(count,count+1);
}
var numbers = textString.substring(0,count);
currentCell.setRichTextValue(SpreadsheetApp.newRichTextValue().setText(numbers)
.setTextStyle(1, count, style).build());
};
In retrieving my textString, is there a way to do it without using "getRichTextValue()"?
In writing the new text (numbers), is there a way to do that without using "setRichTextValue()"? And to do it without specifying the style?
In my while loop, I use char<10. This works, but I'm not sure why. char is a one character string, right? The character is a number, but I am thinking I shouldn't be able to compare with a number because it's a string? Also, it actually lets blank spaces through as well, so I know something is wrong. What can I do instead?
How can I get the replace function to remove ALL the blank spaces in my textString?
Here is a modified version of your script using Regex.
The reason your code char<10 works is it is comparing the ASCII value of the character with A being 10 and 0 to 9 being ASCII value 0 to 9.
function myFunction() {
var spreadsheet = SpreadsheetApp.getActive();
var currentCell = spreadsheet.getCurrentCell(); // returns a range, no need to activate
var textString = currentCell.getValue();
// use reges to remove all blank spaced
textString = textString.replace(/\s/g,"");
// use regex to get the first string of digits
// match returns an array so we need the first element of the array
var numbers = textString.match(/\d+/)[0];
currentCell.setValue(numbers)
}
Reference
Range.getValue()
Range.setValue()
Regex tester

How to insert a parameter in

I need to insert a parameter into this:
row: workbook.getWorksheet("VittorioZigiotto").getRange("VittorioZigiotto[237]:Vittorioigiotto[241]")
The parameter need to be where now there is "237" and neet to depend on a cell in the workbook. For example, MONEYPAGE1!A1+5. Any ideas?
You can get the value you'd like instead of 237 from MONEYPAGE!A1 by doing something like:
const valueFromMPA1 = workbook.getWorksheet("MONEYPAGE").getRange("A1").getValue(); // use getValue for convenience since it's a single cell
const rowString = `VittorioZigiotto[${valueFromMPA1}]:VittorioZigiotto[${valueFromMPA1 + 5}]`; // this is a js/ts way to construct strings with params
// and then pass that in as the argument ...
const row = workbook.getWorksheet("VittorioZigiotto").getRange(rowString);
I'm not sure of your exact scenario, but also take a look at .getRangeByIndexes (instead of getRange), which lets you pass numeric row/column values instead of having to construct a string argument.

Changes in a temporary variable are affecting the variable that feeds from

I'm designing a Mastermind game, which basically compares 2 lists and marks the similarities. When a colour is found at the right place, a flag making the correct position is added and the item found on the reference list is marked off. The reference list is feeding off an array from another function. The problem is at the mark off, as any changes done to the reference list is changing also the original array, which i don't want it to happen
tempCode = mCode #mCode is the array combination randomly generated from another function
for i in range (len(uCode)): #user input array
for j in range (len(tempCode)): #temp array
if uCode[i] == tempCode[j]: # compare individual chars
if i == j: #compare position
flagMark = "*"
tempCode.insert(j+1, "x") #problem starts here
tempCode.remove(tempCode[j])
fCode.append(flagMark)
When the insert is reached both the tempCode and mCode change which it is not intended.
The code is written in a way should the user enter a combination of the same colours, thus checking the chras(the colours are just letters) and the position, and then mark them of with "x"
As it stands, when it gets to
tempCode.insert(j+1, "x")
the arrays will change to
mCode = ["B","R","x","G","Y"]
tempCode = ["B","R","x","G","Y"]
when I would just want
mCode = ["B","R","G","Y"]
tempCode = ["B","R","x","G","Y"]
See also this answer, which is a different presentation of the same problem.
Essentially, when you do tempCode = mCode, you're not making a copy of mCode, you're actually making another reference to it. Anything you do to tempCode thereafter affects the original as well, so at any given time the condition tempCode == mCode will be true (as they're the same object).
You probably want to make a copy of mCode, which could be done in either of the following ways:
tempCode = mCode.copy()
tempCode = mCode[:]
which produces a different list with the same elements, rather than the same list

Dictionary lookup fails

I am writing an Excel VBA program that validates a school course schedule. A key component is a global dictionary object that keeps track of the course number (the key) and the number of times that course is scheduled (the item). I have successfully created and loaded the dictionary. I'm trying to lookup the value associated with the course key, but have been unable to do so using the one-line examples I've found at this site. I'd like to use this line of code:
intCourseCnt = gdicCourses("BAAC 100")
or
intCourseCnt = gdicCourses.Item("BAAC 100")
but neither work (actually, the "BAAC 100" part is a string variable, but it won't even work if I hardcode a course in.) Instead, I have to use the kludgy loop code below to lookup the course count:
Private Function Check_Course_Dup_Helper(strCourse As String) As Boolean
Dim k As Variant
Check_Course_Dup_Helper = False
' Read thru dictionary. Look to see if only 1 occurrence then jump out.
For Each k In gdicCourses.Keys
If k = strCourse Then
If gdicCourses.Item(k) = 1 Then
Check_Course_Dup_Helper = True
Exit Function
End If
Exit Function
End If
Next
End Function
Is there a way to rewrite this so that I can lookup of the item value without the loop?
Thank you.
Thanks for the prompt replies. Answers below:
David, the gdicCourses("BAAC 100") code value while the program is running is "empty" which makes the receiving variable equal to 0. The result is the same if I use strCourse variable. Also, the dictionary populating code is shown below. I do not believe it is a problem because I can correctly access the values elsewhere in the program where For-Each-Next loops that use a range variable are employed. Whitespace and non-printable characters are not present.
My guess is that I need to use a range to reference the position in the dictionary rather than a string. I've tried pretty much every combination of this that I can think of, but the value is still "empty".
Set gdicCourses = New Scripting.Dictionary
For Each c In Worksheets("Tables").Range("combined_courses").Cells
If Not (gdicCourses.Exists(c)) Then
gdicCourses.Add c, (Application.WorksheetFunction.CountIF(Range("MWF_Table_Full"), c
(Application.WorksheetFunction.CountIf(Range("TTh_Table_Full"), c)))
End If
Next

Get handles as a number in order to apply function and operate mathematicaly

The program asks for input in gui editbox as a value, then it takes this value and applies the equation to get the pressure. I haven't been able to do so and I heard from some classmates that matlab takes the input as a string and doesn't operate strings.
get(handles.spl,'String') this is how I get the value, I tried get(handles.spl,'Double') instead but it didn't work, also tried str2double.
I don't know what else to try, I'm also pretty new in programming.
I'd appreciate the help, thanks.
You are correct that the uicontrol String property returns...a string. So you'll need to convert it to a number using str2double.
u = uicontrol('style', 'edit', 'String', '42');
strvalue = get(u, 'String');
numvalue = str2double(strvalue);
% 42

Resources