Difference between two strings in VBScript - string

I need a way to find the difference between two strings in a Windows application using VBScript. One of the strings is known but the second one is completely unknown during coding. I know there are functions like StrCompare, InStr etc. but these require you to know the second string also during coding.
Explanation:
There is a text box in the screen and there are several buttons in the same screen. As and when the buttons are clicked, the text in the text box changes depending on the button clicked. Is there a way to find the changes made to the text after the button is clicked ? Basically I need to get the text entered due to the button click. Is there a simple way to do this or it requires complex coding ?
Thanks in Advance.

It depends on your application and the format of the new string.
If you need to find the text appended to the original string, you could take the new text and simply replace the first occurrence of the original string with an empty string:
Dim strOld, strNew, strDiff
strOld = "Apple"
strNew = "Apple, Orange"
strDiff = Replace(strNew, strOld, "", 1, 1)
WScript.Echo strDiff
Sample output:
, Orange
Or if you need to get the appended text without the preceding comma, you could use something like this:
strDiff = Replace(strNew, strOld + ", ", "", 1, 1)

To access (read/write) the content of a HTML text input you need to get the HTML element (document.all.<Name/Id> or document.getElementById(<Name/Id>) and its .value; as in this demo:
<html>
<head>
<Title>readtext</Title>
<hta:application id="readtext" scroll = "no">
<script type="text/vbscript">
Function Change()
document.all.txtDemo.value = "Changed Value"
End Function
Function Check()
Dim txtDemo : Set txtDemo = document.getElementById("txtDemo")
Dim sDemo : sDemo = txtDemo.value
Select Case LCase(Trim(sDemo))
Case "initial value"
MsgBox "still: " & sDemo
Case "changed value"
MsgBox "now: " & sDemo
Case Else
MsgBox "surpise: " & sDemo
End Select
End Function
</script>
</head>
<body>
<input type="text" id="txtDemo" value="Initial Value" />
<hr />
<input type="button" value="Change" onclick="Change" />
<input type="button" value="Check" onclick="Check" />
</body>
</html>

Related

readonly cells ... .. ......

Code is required
which type of value format is needed to enter in Excel cell, with one example
these are the coding stuff, also provided you an image where any can visualize how the problem look like. And in this problem we can't just use .SendKeys here it is more typical, because it have the Date-Month-Time, so help me out in this.
I tried, after removing "readonly" word in HTML .. then its working fine, but this is not the way can you edit in this code,
Sub google_search()
Dim row As Integer
row = 2
Dim bot As WebDriver
Set bot = New WebDriver
Dim GenderDD As Selenium.WebElement
bot.Start "chrome"
bot.Get "https://abcd.com/"
bot.FindElementbyName("sample_cdate").SendKeys "Value"
Stop
End Function
Also giving Inspect of Targeted Site, for the reference
<input type="text" class="form-control datetimepicker" name="sample_cdate" id="sample_cdate" placeholder="Date and Time of Sample Collection" **readonly**="">
I tried, after removing "readonly" word in HTML .. then its working
fine, but this is not the way can you edit in this code
You should replace .SendKeys() method:
'bot.FindElementbyName("patient_id").SendKeys Sheet1.Cells(row, 3).Value
bot.ExecuteScript "arguments[0].setAttribute('value', arguments[1])", _
Array(bot.FindElementById("sample_cdate"), _
Format(Sheet1.Cells(row, 16).Value, "yyyy-mm-ddThh:mm:ss"))
As a readonly element, similar as on graphic WebBrowser, you cannot type input using .SendKeys(), but you can use JavaScript to set .Value attribute through programming.
As you show, your input id may be id="sample_rdate", not sample_cdate.

Need help selecting multiple items in combobox in IE, using VBA

I am having an issue with one part of my automation job, and that is selecting ALL the options in a combobox, on a webpage, using VBA and IE.
This code selects ONE item in the combo box
Set frm = HTMLDoc.getElementsByName("UFG.USER_TYPES")(0)
frm.Value = "AUT"
However, when I try to select multiple items, it just selects the last one, not all of them.
Here is the code from the web page
<p id="DispFormCollapsible.Rc10"class="formrow" >
<span id="DispFormCollapsible.Rc10.C1" class="querytextleft">
<label for="UFG.USER_TYPES" id="LabelForContro123"class = "simpletext" >
Accessible Types:<span class="redstar">*</span></label></span>
<span id="DispFormCollapsible.Rc10.C2" class="querytextright">
<span class="labelColumn_combo">
<span class="labelColumn_combi_brdr">
<select name= "UFG.USER_TYPES" multiple= "true" class = "dropdownexpandalbe"
id="UFG.USER_TYPES" title = "Accessible Financial Transaction Types">
<option value="AUT" title="ACTIVE USER TYPE1" >TYPE1</option>
<option value="SET" title="Selective User Type" >TYPE2</option>
<option value="TST" title="Test User Type" >TEST3</option>
</select></span></span>
<input type ="hidden" name= "UFG.USER_TYPES" value="NULL" >
</span></p>
Here is my VBA line to select an item
Set frm = HTMLDoc.getElementsByName("UFG.USER_TYPES")(0)
frm.Value = "AUT"
What I need it to do, is select all the "option values" in the combobox. I think it needs to be an array maybe, or some other way. I've tried searching, but I'm getting nowhere. Any help appreciated. Thx
Tried the following, but get an error 91 Block not set. I've also tried using the Values "AUT" in the children, and when doing that I don't get an error, but it doesn not select anything.
With HTMLDoc.getElementsByName("Select")(0)
.Children(1).Selected = True
.Children(2).Selected = True
.Children(3).Selected = True
End With
Also tried the following, this doesn't give an error, but only selects the first option in the list.
With HTMLDoc.getElementsByName("UFG.USER_TYPES")(0)
.Children(AUT).Selected = True
.Children(SET).Selected = True
.Children(TST).Selected = True
End With
This is strange, when I use this code, it selects the first two in the list, but not the third.
With HTMLDoc.getElementsByName("UFG.USER_TYPES")(0)
.Children(all).Selected = True
End With
With HTMLDoc.getElementsByName("UFG.USER_TYPES")(0)
.Children(0).Selected = True
.Children(1).Selected = True
.Children(2).Selected = True
End With
The above code fixed it... whoopie!

google app script for sheets - select multiple list values and record in same cell

I'm trying to replicate something I was able to do in Excel in Google Sheets: Select multiple list values and record in same cell.
I used this video:
https://www.youtube.com/watch?v=8x6YUsl7Ld4&feature=youtu.be
And this code:
Private Sub Worksheet_Change(ByVal Target As Range)
'Code by Sumit Bansal from www.trumpexcel.com
' To Select Multiple Items from a Drop Down List in Excel
Dim Oldvalue As String
Dim Newvalue As String
On Error GoTo Exitsub
If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
GoTo Exitsub
Else: If Target.Value = "" Then GoTo Exitsub Else
Application.EnableEvents = False
Newvalue = Target.Value
Application.Undo
Oldvalue = Target.Value
If Oldvalue = "" Then
Target.Value = Newvalue
Else
Target.Value = Oldvalue & ", " & Newvalue
End If
End If
Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True
End Sub
And managed to get it working in Excel, only to find that the functionality would be lost in Google Sheets.
Please could you tell me the equivalent code in Google apps script and where to place it?
Here's the script to do the same through google-apps-script. Caveats though are
1. Data Validation should be enabled to Show warning and not Reject Input as shown below
2. After selecting multiple items, the Cell in consideration would show a warning.(I couldn't figure out how to turn this off easily).One way to lessen the annoying warning on the cell is to put a help context for the cell "Ignore any warnings" by checking the box Show validation help text: in the image above.
3. The behavior is applied to ALL ranges where there is data validation, so please take due care to apply ONLY to ranges that you care about.
function onEdit(e){
var editedRange=e.range;
var rule = editedRange.getDataValidation();
if(rule!=null) //Act only if the cell has a data validation
if (!(e.value.equals("") || e.oldValue == null)) //No need to do anything funky if user clears everything or if previous contents were empty
if(e.oldValue.indexOf(e.value) !=-1) //Check if new selected value has already been chosen before
editedRange.setValue(e.oldValue) //If already chosen then don't select again.
else
editedRange.setValue(e.oldValue+","+e.value) // Show old+new selection.
}
onEdit is a Simple trigger function that gets called every time there is an edit to the Spreadsheet(any individual Sheets ).
e is the Event Object that contains information about the edit that happened.
You can find more documentation about the same here.
Also this might help if you want to programmatically set a Data Validation.
You could create a dialog to show every available option as checkboxes and set the cell data based on the user selection.
Here is some example data:
and here how such dialog would behave:
To do that you must first create a script file with four functions. One to expose a menu to the dialog, another to show the dialog, a third to process and pass the options to the dialog, and the last one to set data in the cell sent from the dialog. See the code bellow:
function onOpen() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const multiselectMenu = {name: 'Select multiple', functionName: 'showSelectDialog'}
ss.addMenu("My Scripts", [multiselectMenu]);
}
function showSelectDialog(){
const template = HtmlService.createTemplateFromFile('dialog');
template.optionsData = getOptionsFromCurrentCell();
const html = template.evaluate();
SpreadsheetApp.getUi().showModalDialog(html, 'Select multiple');
}
function getOptionsFromCurrentCell(){
const validOptions = SpreadsheetApp
.getActiveRange() // everything that is selected
.getDataValidation() // all validation rules for that
.getCriteriaValues()[0] // the first criteria
.getValues() // the value for this criteria
.map(value => value[0]); // flatten in an one dimension array
const selectedOptions = SpreadsheetApp
.getActiveRange()
.getCell(1, 1) // first selected cell in the range
.getValue()
.split(',') // convert the cell string into an array
.map(str => str.trim()); // remove unwanted whitespace
const optionsData = validOptions.map(option => {
return {
value: option,
isSelected: selectedOptions.includes(option)
}
})
return optionsData;
}
function setOptionsForCurrentCell(selectedOptions){
const hasOptions = Array.isArray(selectedOptions)
&& selectedOptions.length > 0
const cellData = hasOptions
? selectedOptions.join(',') // creates a comma separated string
: '';
const cell = SpreadsheetApp.getActiveRange().getCell(1, 1);
cell.setValue(cellData);
}
Then you create a Html file inside the script editor to render the dialog and pass the selected options back to the spreadsheet. See:
<!DOCTYPE html>
<html>
<body>
<? for (const option of optionsData) { ?>
<input
type="checkbox"
class="option"
value="<?= option.value ?>"
<?= option.isSelected && "checked" ?>
>
<label><?= option.value ?></label><br>
<? } ?>
<div style="margin-top:10px;">
<input
type="button"
value="all"
onclick="setAll('check')"
/>
<input
type="button"
value="clear"
onclick="setAll('clear')"
/>
<input
type="button"
value="cancel"
onclick="google.script.host.close()"
/>
<input
type="button"
value="apply"
onclick="apply()"
/>
</div>
<script>
function setAll(value) {
const optionsEl = document
.querySelectorAll(".option");
for (const checkbox of optionsEl) {
checkbox.checked = value === 'check';
}
}
function apply(){
const checkedEls = document
.querySelectorAll(".option:checked");
const selectedValues = [];
for (const checkbox of checkedEls) {
if (checkbox.checked) {
selectedValues.push(checkbox.value);
}
}
google.script.run
.setOptionsForCurrentCell(selectedValues);
google.script.host.close();
}
</script>
</body>
</html>
That should work. If you want a step-by-step guide for this solution, check this post.

Web scraping worked fine in IE 9 but breaks in IE 11

I had a procedure that scraped information from a website in IE9 however after updating to IE11 the procedure breaks when trying to enter a piece of data into
an input box on the webpage. The code recognizes the field and it is listed as on object when I debug but when I try to enter a value into the box using CUSIP.value it does not enter anything on the webpage. I think it has something to do with the source being updated after the browser was updated. I could have sworn that the identifier for "txtCusipNo" in the HTML was listed as an ID instead of a Name. Any help is appreciated. Thanks.
HTML from website
<td class="tbl1">
<INPUT TYPE="TEXT" NAME="txtCusipNo" VALUE="" CLASS="input" SIZE="11" MAXLENGTH="9">
<img src="/RDPANN/pbs/images/lookup.gif" border="0" alt="Open Security Finder" align="absmiddle"> <IMG NAME="txtCusipIMG"SRC="/RDPANN/pbs/images/req.gif" ALIGN="ABSMIDDLE">
</td>
VBA code
Private Sub EnterCUSIP()
Retry:
Set CUSIP = Doc.getElementById("txtCusipNo")
Err.Clear
valA = ActiveSheet.Cells(row, 1)
On Error Resume Next
CUSIP.Value = ActiveSheet.Cells(row, 1) 'insert CUSIP
If Err.Number = 91 Then GoTo Retry
Set CurrentWindow = IE.document.parentWindow
Call CurrentWindow.execScript("javascript:processForm(document.forms.frmSearchEntry)") 'Search (hit enter)
If Err.Number = -2147352319 Then Exit Sub
On Error GoTo 0
Do While (IE.Busy Or IE.READYSTATE <> READYSTATE.READYSTATE_COMPLETE):DoEvents: Loop
End Sub
If you suspect that the HTML source has been changed and may make unannounced changes in the future, I would recommend switching to the ie.Document.All.Item property.
Doc.all.Item("txtCusipNo").Value = 123
The .Item identifier can be either an ID or a Name, there is no distinction between the two. However, I would be concerned that the identifying factor (e.g. txtCusipNo) may not be unique on that page. Yes, it is supposed to be but a growing number of HTML developers are using code like divs(0).getElementById("txtCusipNo") and divs(1).getElementById("txtCusipNo").

search vb.net form using sqldatasource

This is my first time creating a search form. I am trying to create a form currently with two fields to enter last and first name. When the button is clicked I would like to get results from the table. Sounds simple. I browsed the web but am not able to wrap my head around how to do it using sqldatasource. I am not able to connect how to trigger the query with the click of the button. I have this:
<asp:SqlDataSource ID="SearchPDS" runat="server" ConnectionString="<%$ ConnectionStrings:IDBConnectionString %>"
SelectCommand="SELECT * from [tblPatron] WHERE LName = #LName" >
<SelectParameters>
<asp:ControlParameter ControlID="txtLName" Name="LName" ConvertEmptyStringToNull="false" PropertyName="Text"/>
</SelectParameters>
</asp:SqlDataSource>
I am trying to display the results in a grid:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SearchPDS" AutoGenerateColumns="true">
</asp:GridView>
Also I wrote code behind for the onclick event for the button:
Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
SearchPDS.SelectCommand = "Select * From tblPatron where LName = #LastName"
SearchPDS.SelectParameters.Add("LastName", txtLName.Text)
SearchPDS.DataBind()
GridView1.DataBind()
End Sub
I changed the sqlsource code to
<asp:SqlDataSource ID="SearchPDS" runat="server" ConnectionString="<%$ ConnectionStrings:IDBConnectionString %>"
SelectCommand="SELECT * from [tblPatron]">
</asp:SqlDataSource>
and running the query for the onclick event.
Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim strSearch As String
strSearch = "SELECT * FROM tblPatron WHERE (LName Like '%" + txtLName.Text.ToString() + "%')"
strSearch = strSearch + "AND (FNAME Like '%" + txtFName.Text.ToString() + "%')"
SearchPDS.SelectCommand = strSearch
GridSearchResults.Visible = True
End Sub
This seems to be working fine. Is there any sleek way of doing the same job?
Thanks
~ Nita

Resources