I am trying to find the number of items in a variable, I tried to create somewhat of a while loop to test if the item of the variable exists, if it does then go to the next item and test if it exists, this repeats until the item does not exist, then it displays the current item number, which should be the final item of the variable.
Here is my code:
set stuff to "123456789"
set x to "1"
set num to item x of stuff
if exists item x of stuff then
repeat while exists item (x + 1) of stuff
if exists (item x of stuff) then
set x to (x + 1)
else
set num to x
end if
end repeat
end if
display dialog num
Currently when I run this code I get the error:
"Can’t get item 10 of "123456789"."
Which I understand tells me that 10 is the last item of this variable but the information does me no good in the form of an error message. Thanks in advance
How to find the number of items in a variable? (AppleScript)
The clue's in the question:
set variable to "123456789"
return the number of items in the variable --> 9
As already stated by red_menace, you can also quantify data objects using the length property (for list, record, or text objects), or by using the count command, which is superfluous in my view as it ends up accessing the length property anyway.
The AppleScript command count counts the number of elements in an object, for example count of stuff. In addition, classes such as list, record, and text also have a length property, for example length of stuff.
set stuff to "this is a test"
set x to 0
repeat with anItem in (get items of stuff)
set x to x + 1 -- just using x to count
log anItem
end repeat
display dialog "Number of items is " & x & return & "Count is " & (count stuff) & return & "Length is " & (length of stuff)
See the AppleScript Language Guide for more information.
I have a script that has an array of terms. I'd like to create variables based on each term. I'm attempting to count how many times each term is chosen by the user and log a number associated with the term (also from user input).
My history with jQuery leads me to want to do something like this:
set term + "_Count" to term + "_Count" + 1
set term + "_Log" to term + "_Log" + inputNum
However, (obviously) that sort of syntax is not possible with AppleScript. Is there a way to concatenate a string onto a variable name?
-- for more reference, I'm trying to avoid listing every term out as I try to set 2 variables related to each term. I've currently got a long If/Then statement to set each one when the user picks a term.
term: "project"
termCount: 3 -- times activated
termLog: 120 --
minutes
I've been searching everywhere but haven't found anything conclusive for my question. Perhaps I just don't know the proper terms to search or maybe my whole approach is incorrect. Any help would be appreciated.
You really don’t. What you want is a dictionary datatype (aka "hash", "map", "associative array", etc), which store and retrieve values using arbitrary keys (most commonly strings). AS doesn’t have a native dictionary type, but for storing simple value types (boolean, integer, real, string) you can use Cocoa’s NSMutableDictionary class via the AppleScript-ObjC bridge:
use framework "Foundation"
set myDict to current application's NSMutableDictionary's dictionary()
myDict's setValue:32 forKey:"Bob"
myDict's setValue:48 forKey:"Sue"
(myDict's valueForKey:"Bob") as anything
--> 32
Short story:
Variable names are evaluated at compile time. Dynamic variables (evaluated at runtime) are not possible.
It's difficult to give an exact answer without seeing all of your code but you can use Concatenation to define new variables.
If you were to save this following code as an application, the item chosen and the amount of times it has been chosen, get stored in the script and the values get updated.
Again, it's difficult to pinpoint exactly what you need but this is an example of Concatenation and defining how many times an item has been chosen
property theUserChose : {"Project_1", "Project_2", "Project_3"}
property term_1_count : 0
property term_2_count : 0
property term_3_count : 0
property minutes : 120
property term : missing value
set resultValue to choose from list theUserChose ¬
with title "Make Your Choice" OK button name ¬
"OK" cancel button name "Cancel" without empty selection allowed
set resultValue to resultValue as string
if resultValue is item 1 of theUserChose then
set term_1_count to term_1_count + 1
set term to resultValue & "_" & term_1_count & "_" & minutes
else
if resultValue is item 2 of theUserChose then
set term_2_count to term_2_count + 1
set term to resultValue & "_" & term_2_count & "_" & minutes
else
if resultValue is item 3 of theUserChose then
set term_3_count to term_3_count + 1
set term to resultValue & "_" & term_3_count & "_" & minutes
end if
end if
end if
display dialog term
AppleScript beginner here. Searching high and low hasn't led me to the answer yet.
I'm using AppleScript to help run youth wrestling tournaments. Each division (based on age) is broken down into weight classes. For example: Novice 80 or Cadet 105.
Once a certain group of kids is put into a certain division/weight class, those kids get added to a new sheet that contains their bracket (think March Madness bracket but a small number of kids wrestling instead of playing basketball).
I've figured out how to get a group into a new sheet where they populate the bracket, but when this new sheet is created, I don't know how to make AppleScript change the name of the sheet to the correct division/weight class. I'm sure it has something to do with creating variables based on a list of the divisions/weight classes (that I have), but I can't figure out how to do it. Here's the relevant portion of the code:
tell document 1
set active sheet to the last sheet
set thisSheet to make new sheet
set the name of thisSheet to "[Division variable – Weight class variable]"
tell thisSheet
delete every table
end tell
Any ideas on how to make AppleScript name the sheet like I want?
To give you a small example that you're able to visualize what you're going after, heres a small snippet. I think its self explanatory, iterate through a list of titles, then apply the names to the sheets.
set divisionNames to {"Novice", "Cadet"} -- How You Grab These Values Matters
set weightClasses to {"80", "105"} -- These Values Too
tell application "Numbers"
activate
set thisDocument to make new document
tell thisDocument
repeat with i from 1 to count of divisionNames
make new sheet with properties {name:item i of divisionNames & space & item i of weightClasses}
end repeat
end tell
end tell
Alternately, if you're pulling the values from a list as a whole then you could
set sheetTitles to {"Novice 80", "Cadet 105"}
tell application "Numbers"
activate
set thisDocument to make new document
tell thisDocument
repeat with division in sheetTitles
make new sheet with properties {name:division}
end repeat
end tell
end tell
EDIT: In the spirit of helping a low to no budget school/organization.. here's another example answering the second question issued in comments. Again without knowing the structure of your data its hard to give you an exact answer on your specific case. Additionally, here's a link to a site they may help further the advancement on your project. https://iworkautomation.com/numbers/index.html
(*
set sampleKids to {"John Doe", "Jane Doe", "Johnny Foe", "Janie Foe", "Tommy Joe", "Tammy Joe"}
set sampleDivisions to {"Novice-80", "Novice-85", "Cadet-105", "Cadet-110", "Novice-80", "Cadet-105"}
tell application "Numbers"
activate
set thisDoc to make new document with properties {name:"Wrestling Sample"}
tell thisDoc
set the name of sheet 1 to "Sign In Sheet"
tell active sheet
delete every table
set newTable to make new table with properties {row count:(count of sampleKids) + 1, column count:2, name:"Sign In Sheet"}
tell newTable
set value of cell 1 of column "A" to "Name"
set value of cell 1 of column "B" to "Division"
set x to 2
repeat with eachName in sampleKids
set value of cell x of column "A" to eachName
set x to (x + 1)
end repeat
set x to 2
repeat with eachDivision in sampleDivisions
set value of cell x of column "B" to eachDivision
set x to (x + 1)
end repeat
end tell
end tell
end tell
end tell
*)
--********** IGNORE ABOVE THIS LINE IT'S ONLY BUILDING A SAMPLE TABLE **********--
--********** SAVE ABOVE TO ANOTHER SCRIPT FOR TESTING WITH NEW TABLE **********--
(*
ERROR HANDLING ISN'T PRESENT - AN EMPTY CELL IN FIRST COLUMN OR CHOSEN COLUMN WILL THROW AN
ERROR SINCE THEY ARE THE IMPORTANT PIECES OF DATA FOR GRABBING LISTS - SAVE SCRIPT
TO NUMBERS SCRIPT FOLDER OF YOUR CHOICE - ENTER ALL INFO ON FIRST TABLE OF FIRST SHEET OF
DOCUMENT THEN RUN SCRIPT - SCRIPT ACCEPTS ANY AMOUNT OF ROWS OR COLUMNS
*)
tell application "Numbers"
activate
-- Display A Simple Reminder That You're About To Lose Some Existing Data
display dialog "This Script Will Delete All Sheets Except The First Sheet Of This Document Before It Proceeds To Make New Sheets & Tables Based On The First Table Of The First Sheet." buttons {"Cancel", "Start"} default button 2 with icon 1
tell document 1
-- Get A List of the Sheet Names
set sheetNames to name of sheets
-- Start With A Fresh Slate, No Old Sheets
delete (every sheet whose name is not item 1 of sheetNames)
tell sheet 1
-- Grab and Set Future Header Values
set columnHeaders to value of cell of row 1 in table 1
-- Display A List Of Possible Choices To Create New Sheets With From The List We Make Above
set chosenColumn to choose from list columnHeaders with prompt "Which Column Do You Want To Use For New Sheets?" default items item 1 of columnHeaders
set chosenColumn to chosenColumn as text
tell table 1
-- Remove All Empty Rows to Help Prevent Error In Script
set {row_count, col_count} to {count rows, count columns}
set blank_row to {}
repeat with x from 1 to col_count
set blank_row to blank_row & missing value
end repeat
set x to 1
-- Delete Empty Rows In Reverse, It's Logical
repeat with y from row_count to 1 by -1
set row_values to value of cells of row y
if row_values = blank_row then delete row y
end repeat
-- Grab A List of All Divisions for Future Use Depending on Choice From Prompt, excluding the First Row Which Is A Header. If You Selected The First Column, We Have to Handle That Differently
if chosenColumn is item 1 of columnHeaders then
set theDivisions to the value of every cell of column "A" whose value is not chosenColumn
else
set theDivisions to the value of every cell of column named chosenColumn whose value is not chosenColumn
end if
end tell
end tell
-- Start the New "Sheet Making" Loop
repeat with division in theDivisions
-- Make An Empty Blank List At the Start of Every Loop
set matchingDivisions to {}
tell table 1 of sheet 1
-- Get All Rows Matching the Current Division of the Loop We Are On, to Make New Tables With Later
repeat with x from 1 to count of cells
if the value of cell x is division then
-- Put All Data About the Rows We Gathered Above Into the Empty List We Made
set the end of matchingDivisions to value of cells of row of cell x
end if
end repeat
-- Reset x, Because I'm Not Creative and Want to Use It Later
set x to 1
end tell
-- If The Sheet Of the Division We Are On, of the Loop, Doesn't Exist, Make It
if not (exists sheet division) then
make new sheet with properties {name:division}
tell sheet division
-- Start With A Fresh Slate On This New Sheet
delete every table
-- Make the Table With All Relevant Parameters
set currentDivisionTable to make new table with properties ¬
{row count:((count of matchingDivisions) + 1), column count:count of item 1 of matchingDivisions, name:division}
tell currentDivisionTable
set x to 1
-- Set The Header Values from A List We Created Earlier
repeat with theHeader in columnHeaders
set the value of cell x to theHeader
set x to (x + 1)
end repeat
-- Reset x Again, I'm Lazy
set x to 1
-- Set Starting Point to Start Filling The Table, Compensate For Our Headers
set rowIndex to 1
set columnIndex to 0
-- Start Filling The Table With Data, Which Comes From The List Earlier
repeat with x from 1 to count of the matchingDivisions
set rowData to item x of the matchingDivisions
tell row (rowIndex + x)
repeat with i from 1 to the count of rowData
tell cell (columnIndex + i)
set value to item i of rowData
end tell
end repeat
end tell
end repeat
end tell
end tell
end if
end repeat
-- Return To the First Sheet
set the active sheet to the first sheet
-- Display Notification That The Tables Are Done Being Made -- OPTIONAL
display notification "Processing is complete." with title "Numbers Table Converter" subtitle "All Tables Have Been Made." sound name "Hero"
end tell
end tell
Try
set thisSheet to make new sheet with properties {name:"yourname"}
Edit
Some explanation: if your struggling on how to adress third party apps try to load it's library and look up the methods you need. In applescript editor you will find it in the (I guess) menu. Then select the desired app to get the library
The full code modify at below:
set {begCol, endCol} to {2, 17}
set tgtCol to 1
tell application "Numbers"
tell front sheet of front document
tell active sheet
set getVal to rows's cells's value
set myOriginalTable to front table
set itemCode to {"CardNo", "SAL-DAY", "OT15-Money",
"OT2-Money", "OT3-Money", "OTHINC", "P0007", "DILIG", "P0004", "P0003",
"SEV_SPE", "P0011", "SI-SSF", "TI-TAXITEM", "P0022", "P0021", "P0025"} --
change to variable
set Amount to {"CardNo", "SAL-DAY", "OT15-Money",
"OT2-Money", "OT3-Money", "OTHINC", "P0007", "DILIG", "P0004", "P0003",
"SEV_SPE", "P0011", "SI-SSF", "TI-TAXITEM", "P0022", "P0021", "P0025"} --
change to variable
set setCols to 8
end tell
set myNewTable to make new table with properties ¬
{column count:setCols, row count:(count of itemCode) + 1,
header column count:0}
tell myNewTable
set value of cell 1 of column "A" to "cardNo"
set value of cell 1 of column "B" to "emCode"
set value of cell 1 of column "C" to "emName"
set value of cell 1 of column "D" to "itemCode"
set value of cell 1 of column "E" to "itemName"
set value of cell 1 of column "F" to "effDate"
set value of cell 1 of column "G" to "amt"
set value of cell 1 of column "H" to "remark"
set x to 2
repeat with eachAmount in Amount
set value of cell x of column "G" to eachAmount
set x to (x + 1)
end repeat
set x to 2
repeat with eachItemCode in itemCode
set value of cell x of column "D" to eachItemCode
set x to (x + 1)
end repeat
end tell
end tell
end tell
Thank you
According source code above. I found other way for use range select for determine data. But it still incorrect because the code pickup all data to one cell like this.
result after ran script
Could some one able to suggest me?
try
tell application "Numbers" to tell front document to tell active sheet
set delimiter to ","
set selected_table to first table whose class of selection range is range
tell selected_table
set my_selection to the selection range
set begCol to address of first column of my_selection
set endCol to address of last column of my_selection
set begRow to address of first row of my_selection
set endRow to address of last row of my_selection
set getVal to ""
repeat with j from begRow to endRow
repeat with i from begCol to endCol
set getVal to (getVal & (value of cell j of column i of selected_table) as text) & delimiter
set getVal to getVal & return
end repeat
end repeat
end tell
end tell
set AmountVal to {getVal}
tell application "Numbers"
activate
tell front sheet of front document
set myOriginalTable to front table
set setCols to 8
set myNewTable to make new table with properties ¬
{row count:(count of AmountVal) + 1, column count:setCols, header column count:0}
tell myNewTable
set value of cell 1 of column "A" to "cardNo"
set value of cell 1 of column "B" to "emCode"
set value of cell 1 of column "C" to "emName"
set value of cell 1 of column "D" to "itemCode"
set value of cell 1 of column "E" to "itemName"
set value of cell 1 of column "F" to "effDate"
set value of cell 1 of column "G" to "amt"
set value of cell 1 of column "H" to "remark"
set x to 2
repeat with eachAmount in AmountVal
set value of cell x of column "G" to eachAmount
set x to (x + 1)
end repeat
end tell
end tell
end tell
display notification "Already Done!" with title "Numbers"
on error
display dialog "Select a range first and then try again"
end try
In the program below r is initialized as a rounded random number and the user is prompted to guess. If the user guesses correctly there is one prompt Else there is another prompt. The code looks right but when ran the Else case is chosen whether the user got the number right or not. Please help I have read over it so many times that it hurts.
Set WshShell = WScript.CreateObject("WScript.Shell")
'This script is designed to create a random number, and have a user guess the number
'If the user guesses the number incorrectly, negatively impact the users system
'if the user guess the number correctly, do nothing
dim InputValue
dim UserInput
'create a random number
dim r
randomize
r = int(rnd * 10)+1
'Allow the user to guess what number is correct
Input = inputbox ("Choose a number from one to ten, and choose wisely ;)", "Type a number.")
InputValue = Input
'Provide the user with feedback as to what his/her choice was and what the number actually was.
UserInput = "You typed " & InputValue & "." & " The number was " & r & "."
'echo the random generated number for test purposes
WScript.Echo r
Select Case InputValue
Case r
WScript.Echo "No action"
Case Else
WScript.Echo "Negative Action"
End Select
The issue is that InputValue is a String type because that's what's returned by the InputBox function and r is an Integer, so when you compare InputValue to r, you're comparing a string to an integer, i.e. apples to oranges.
Proof of concept:
Dim x
x = "5"
Dim y
y = 5
Select Case x
Case y
MsgBox "Yes"
Case Else
MsgBox "No" 'this is what happens.
End select
VBScript is not a strongly-typed language, i.e. it does not know about types really at all -- well, it kind of knows. It treats every variable as one type called a "variant" which itself can then have an affinity to a more specific type but in a very confusing and error-prone way. I'd say you should read this to learn more about it.
You can get into a lot of trouble with this unless you always make sure you know what "types" you're working with.
Try changing it to this:
InputValue = CInt(Input)
Now you're converting the "string" into an "integer" (the variables are both still actually "variants" but they have the same underlying affinity to integer). However, you want to be careful because someone might input a value that is not able to be converted to an integer, e.g. hello, and thus you'll get an error on this line. You will need to do some error checking first before converting it.
I need a help in VBScript or either in QTP for the below case.
For example:
I have nearly 40 items in the weblist. I have only one item in the Excel sheet that is one among the 40 in the weblist. If I run the script, the one in the Excel should be select in the weblist. How do I perform this? I tried many scenarios, but couldn't get it to work.
Below are some of the sample pieces of code I tried in QTP:
ocount=Browser("name:=brw").Page("title:=brw").WebList("htmlid:=tabContainerBrandSite_123&rtyoh").GetROProperty("items count")
msgbox ocount
var7=mySheet2.Cells(2,"C")
For k=2 to ocount
ocount2=Browser("name:=brw").Page("title:=brw").WebList("html id:=tabContainerBrandSite_123&rtyoh").GetItem(k)
msgbox ocount2
merchantName = DataTable("Merchant_Name","Global") 'an example if value is saved in global sheet
items_count = Browser("Sarit").Page("Sarit_2").WebList("txtVendorCode").GetROProperty("Items Count") 'This will get all the items from your weblist.
i = 1
Do
webListName = Browser("Sarit").Page("Sarit_2").WebList("txtVendorCode").GetItem(i)
'this will get first value from the web list
If merchantName = webListName Then 'comparing first value from your value from global sheet
Browser("Sarit").Page("Sarit_2").WebList("txtVendorCode").Select(i) 'selects that value
Exit do 'because it has found your only value from the local sheet, it exits
else
i = i + 1
End If
Loop While i <= items_count