How can I use iteration to make this vbnet code more efficient? - vb.net

Function set_bar_positions()
bar_x(0) = delocateX(bar1.Left)
bar_y(0) = delocateY(bar1.Top)
bar_x(1) = delocateX(bar2.Left)
bar_y(1) = delocateY(bar2.Top)
bar_x(2) = delocateX(bar3.Left)
bar_y(2) = delocateY(bar3.Top)
This snippet from one of my functions show what I'm trying to do. These lines repeat almost identical until the end of the function where this is called:
bar_x(29) = delocateX(bar30.Left)
bar_y(29) = delocateY(bar30.Top)
I have tried iterating this functions by doing stuff like this, but now I know I can't:
Dim num As Integer = 0
bar_x(num) = delocateX(bar(num)).Left)
I am trying to make this code more efficient and have less lines. Anyone have an idea I can implement?

You can use Controls.Find
For i = 0 To 29
Dim cs = Me.Controls.Find("bar" & i.ToString(), True)
If cs.Any() Then
Dim c = cs.First()
bar_x(i) = delocateX(c.Left)
bar_y(i) = delocateY(c.Top)
End If
Next

Related

Expanding a SAP Tree

I'm using UFT (vbscript) to automate a process between SAP and a Web page. Using SAP transaction S_ALR_87013534, I have a piece of code in UFT that will expand the tree completely and extract the value associated with one of the order numbers:
set tree = SAPGuiSession("Session").SAPGuiWindow("Execute Drilldown Report").SAPGuiTree("TableTreeControl")
tree.OpenItemContextMenu "PRJ "&projNum,"PRJ "&projNum
tree.SelectMenuItemById "&EXPAND"
tree.SelectNode "PRJ "&projNum
colKey_plan1 = getColNameFromTitle(tree, "Plan 2--Overall")
rowContainingOrdNum = findBudget(tree, ordNum)
plannedProjectBudget = tree.Object.GetItemText(tree.Object.GetAllNodeKeys(rowContainingOrdNum(0)), colKey_plan1)
Function getColNameFromTitle(tree, title)
set colNames = tree.Object.GetColumnNames
For i = 1 To (colNames.length-1)
selectedColTitle = tree.Object.GetColumnTitleFromName(colNames(i))
If selectedColTitle = title Then
getColNameFromTitle = colNames(i)
Exit For
End If
Next
End Function
Function findBudget(tree, ordNum)
rowContainingOrdNum = Array()
Set columnNames = tree.Object.GetColumnNames()
set columnKeys = tree.Object.GetColumnCol(columnNames(0))
For i = 1 To (columnKeys.length-1)
If InStr(columnKeys(i), ordNum)>0 Then
AddItem rowContainingOrdNum, i
Exit For
End If
Next
findBudget = rowContainingOrdNum
End Function
Function AddItem(arr, val)
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = val
AddItem = arr
End Function
This works perfectly, but when I use a different report, S_ALR_87013543, it's still recognised as a tree but the above code doesn't work as there is no EXPAND option at the Object heading. I'm not very familiar with SAP and all their trees and how to use automation with it, so any guidance or tips are appreciated.
Left is the report I need to expand, and right is the report the code works with:
Solution:
Set TreeObj = SAPGuiSession("Session").SAPGuiWindow("Actual/Plan/Variance").SAPGuiTree("TableTreeControl").Object
Set AllValues = TreeObj.GetAllNodeKeys
Count = AllValues.Count
Found = 0
For i = 0 to Count-1
NodeText = TreeObj.GetNodeTextByKey(AllValues(i))
If NodeText = WBSelement Then
Found = 1
Exit For
End if
Next
If Found = 1 Then
SAPGuiSession("Session").SAPGuiWindow("Actual/Plan/Variance").SAPGuiTree("TableTreeControl").SelectNode WBS
End If

Variable that depends on another variable VBA

I have an interesting question about referencing another variable based on another variable in an array.
Below is my code:
Dim company, price, sdev, mean, random
Dim companies
companies = Array("mm", "tgt", "boog")
mm_price = 0
mm_mean = 0
mm_sdev = 0
tgt_price = 0
tgt_mean = 0
tgt_sdev = 0
boog_price = 0
boog_mean = 0
boog_sdev = 0
For i = 1 To 3
company = companies(i)
mean = company & "_mean"
sdev = company & "_sdev"
Next i
Now, the issue occurs when I attempt to define the "mean" and "sdev" variables, as they will not use the "0" value, but instead give it the string name "mm_mean" etc. mm_mean = 0, therefore, I want mean = 0 when i = 1. Clear?
Thanks, and let me know. It is a rather strange question, and the code is cut from many different functions, so if it doesn't make sense as to why I am doing this, my apologies. I tried to make it as simple as possible so it wouldn't confuse the answerer.
This is a good example of when custom data-structures (aka "record types", "structs") should be used to group related data together. In VBA the syntax is Type:
Type Company
Name As String
Price As Currency
Mean As Double
SDev As Double
End Type
Public Sub CalculateCompanyInfo()
Dim companies(3) As Company
companies(0).Name = "mm"
companies(0).Price = 123
companies(1).Name = "tgt"
companies(1).Price = 456
companies(2).Name = "boog"
companies(2).Price = 789
For i As Integer = 0 to UBound(companies)
companies(i).Mean = ...
companies(i).SDev = ...
Next i
End Sub
Where ... means whatever custom calculation you need to do to get that value.

Do-While loop (VBA) not looping

so I thought this would be a simple logical problem, but for the life of me I cannot find the issue with this code block. I have checked around on Stack for a solution, but all other do/while loop problems appear to be primarily with other languages.
What I am trying to do is simply loop through an array & add a new worksheet for each element in the array that is not null. Pretty simple right? Yet for some reason it simply loops through once and thats it.
Here is the code block:
Dim repNames() As String
Dim x As Integer
x = 25
ReDim repNames(1 To x)
repNames(1) = "Ahern"
repNames(2) = "Castronovo"
repNames(3) = "Glick"
repNames(4) = "Fields"
repNames(5) = "Murphy"
repNames(6) = "Sleeter"
repNames(7) = "Vivian"
repNames(8) = "Walschot"
repNames(9) = "Wilson"
Dim i As Integer
i = 1
Do 'Loop keeps creating only 1 new sheet. Should create 9.
Worksheets.Add.Name = repNames(i)
i = i + 2
Loop While repNames(i) <> Null
I believe the problem is with this line: Loop While repNames(i) <> Null,
but obviously the logical test seems to hold up.
Any help would be hugely appreciated!
As others note, Null is not the comparison you want to make. Testing anything for equivalence with Null will return Null -- even ?Null = Null returns Null, which is why your loop is exiting early. (Note: To test for a Null, you need to use the IsNull function which returns a boolean, but that is NOT how you test for an empty string.)
In VBA, to test for a zero-length string or empty string, you can use either "" or vbNullString constant, or some people use the Len function to check for zero-length.
Rectifying that error, as originally written in your code, your logical test should abort the loop if any item is an empty string, but none of the items are empty strings (at least not in the example data you've provided) so you end up with an infinite loop which will error once i exceeds the number of items in the repNames array.
This would be probably better suited as a For Each loop.
Dim rep as Variant
For Each rep in repNames
Worksheets.Add.Name = rep
Next
If you need to skip empty values, or duplicate values, you can add that logic as needed within the loop:
For Each rep in repNames
If rep <> vbNullString 'only process non-zero-length strings
Worksheets.Add.name = rep
End If
Next
Etc.
Firstly, you should be comparing to vbNullString. This loops multiple times:
' Declare variables
Dim repNames() As String
Dim x As Integer
Dim i As Integer
' Set data
x = 25
ReDim repNames(1 To x)
repNames(1) = "Ahern"
repNames(2) = "Castronovo"
repNames(3) = "Glick"
repNames(4) = "Fields"
repNames(5) = "Murphy"
repNames(6) = "Sleeter"
repNames(7) = "Vivian"
repNames(8) = "Walschot"
repNames(9) = "Wilson"
' Loop through items
i = 1
Do
Worksheets.Add.Name = repNames(i)
i = i + 2
Loop While repNames(i) <> vbNullString
There is one more problem – why i = i + 2 ? In your question you say you wanted the loop to execute 9 times, but using i = i + 2 skips every other item. If you indeed want to loop through every item:
Do
Worksheets.Add.Name = repNames(i)
i = i + 1
Loop While repNames(i) <> vbNullString
Here you go, I have changed the loop conditional, and changed i=i+2 to i=i+1. A regular while loop would be better than a do while encase the first element is empty
Dim repNames()
Dim x As Integer
x = 25
ReDim repNames(1 To x)
repNames(1) = "Ahern"
repNames(2) = "Castronovo"
repNames(3) = "Glick"
repNames(4) = "Fields"
repNames(5) = "Murphy"
repNames(6) = "Sleeter"
repNames(7) = "Vivian"
repNames(8) = "Walschot"
repNames(9) = "Wilson"
Dim i As Integer
i = 1
Do While repNames(i) <> ""
Worksheets.Add.Name = repNames(i)
i = i + 1
Loop

Submitchanges after a loop - only last record saved

The following code works, but it only saves the last record in the loop, and I can't figure out why. I think the Submitchanges() is in the right place, at the end of the loop. Can someone please show me what's wrong? Thanks.
Sub POPULATE_CHAIN()
Dim newChain As New CHAIN
Dim dpSTRIKE As Integer
'get list of Options Contracts
Dim lstOPT = From Z In DATA.OPTIONs, X In DATA.UDLies
Where X.UDLY_SYM = Z.UDLY_SYM
Select Z.CONTRACT, Z.STRIKE_GAP, X.UDLY_LAST
Dim dctOPT = lstOPT.ToDictionary(Function(Z) Z.CONTRACT)
For Each key In dctOPT.Keys
For COUNT = 1 To 5
dpSTRIKE = 1850 + 5 * COUNT
Dim lkup = From Z In DATA.CHAINs
Select Z
Dim RCD_EXISTS As Boolean = lkup.Any(Function(Z) Z.CONTRACT = dctOPT(key).CONTRACT And Z.P_C = "C" And Z.STRIKE = dpSTRIKE)
If RCD_EXISTS = False Then
newChain.CONTRACT = dctOPT(key).CONTRACT
newChain.P_C = "C"
newChain.STRIKE = dpSTRIKE
DATA.CHAINs.InsertOnSubmit(newChain)
Else
newChain.CONTRACT = dctOPT(key).CONTRACT
newChain.P_C = "C"
newChain.STRIKE = dpSTRIKE
End If
Next
Next
DATA.SubmitChanges()
End Sub
Dim newChain As New CHAIN
should be inside Fore Each, exactly inside second for.
Since it is declared outside the loop, it will be detached from table and attached again to table. So it will be inserted only in last row.

Cant figure out how to merge variables vb.net

I am creating a for each loop to take the words from a string and place them each into a text box. The program allows for up to "9" variables What I am trying to attempt is.
Foreach word in Words
i = i +1
Varible & i = word
txtCritical1.Text = variable & i
any ideas on a way to make this work?
Have a look through the MSDN article on For Each. It includes a sample using strings.
https://msdn.microsoft.com/en-us/library/5ebk1751.aspx
So i went with a simple if statement this does the trick. Each text box is filled in.
Dim details As String = EditEvent.EditDbTable.Rows(0).Item(13).ToString()
Dim words As String() = details.Split(New Char() {"«"})
Dim word As String
For Each word In words
i = i + 1
v = word
If i = 1 Then
txtCritical1.Text = v
ElseIf i = 2 Then
txtCritical2.Text = v
ElseIf ....
ElseIf i = 9 then
txtCritical2.text = v
Else
....
End If
Next