I have a project where the user pulls up a specific URL where the values for Dept, Queue, and Day change by what hyperlink they choose. For example, they would click on a hyperlink and the URL would be something like:
http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=DeptOne&Queue=18&Day=0
The next hyperlink could be:
http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=DeptFive&Queue=13&Day=9.
I would like to use InStr to find Dept, Queue, and Day within the URL, then set their values to variables, such as UDept, UQueue, and UDay. Depending upon these values, the user can then copy a specific ID number that can only be found on the URL with these values. The end result would be a search for the URL:
http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=UDept&Queue=UQueue&Day=UDay
Here's my code so far:
Option Explicit
Dim objIE, objShell, objShellWindows
Dim strIDNum, strURL, strWindow, strURLFound, WShell, i
strURL = "http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=DeptOne&Queue=18&Day=0"
strWindow = "Workflow Process"
Set objIE = CreateObject("InternetExplorer.Application")
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
Set WShell = CreateObject("WScript.Shell")
strURLFound = False
'To fix item not found error
For Each objIE in objShellWindows
Next
For i = 0 to objShellWindows.Count - 1
Set objIE = objShellWindows.Item(i)
On Error Resume Next
If InStr(Ucase(objShellWindows.Item(i).LocationURL), Ucase(strURL)) Then
If InStr(Ucase(objShellWindows.Item(i).FullName), "IEXPLORE.EXE") Then
If Err.Number = 0 Then
If InStr(objShellWindows.Item(i).document.title, (strWindow)) Then
strURLFound = True
Exit For
End If
End If
End If
End If
Next
WShell.AppActivate strWindow
WScript.Sleep 300
strIDNum = objIE.document.getElementByID("ID_PlaceHolder").value
Thank you in advance to anyone who can help me with this.
Have you considered using a regular expression?
dim re, s
dim matches
s = "http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=DeptFive&Queue=13&Day=9"
Set re = new RegExp
re.Pattern = ".*?Dept=(\w+)&Queue=(\d+)&Day=(\d+)$"
Set matches = re.Execute(s)
Dim uDept, uQueue, uDay
uDept = matches(0).submatches(0)
uQueue = matches(0).submatches(1)
uDay = matches(0).submatches(2)
Msgbox join(array("uDept = " & uDept, "uQueue = " & uQueue , "uDay = " & uDay), vbNewLine)
' Output:
' uDept = DeptFive
' uQueue = 13
' uDay = 9
To replace you can also use a Regular Expression:
Set re = new RegExp
s = "http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=DeptFive&Queue=13&Day=9"
newDept = "DeptFourtyTwo"
newQueue = 404
newDay = 12
re.Pattern = "(Dept=)\w+"
newUrl = re.Replace(s, "$1" & newDept)
re.Pattern = "(Queue=)\d+"
newUrl = re.Replace(newUrl, "$1" & newQueue)
re.Pattern = "(Day=)\d+"
newUrl = re.Replace(newUrl, "$1" & newDay)
msgbox newUrl
' output:
' http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=DeptFourtyTwo&Queue=404&Day=12
' Alternatively you can replace everything at once if the order and presence of
' parameters is guaranteed:
re.Pattern = "(Dept=)\w+(&Queue=)\d+(&Day=)\d+"
MsgBox re.Replace(s, "$1DeptFourtyTwo$2404$312")
This only using Instr and Mid Function's
s="http://www.myworkplace.com/UserPlatform/User/Process.aspx?Dept=DeptFive&Queue=13&Day=9"
a = InStr(s, "?") 'We get the value until ?
d1 = Mid(s, a)
c1 = InStr(d1, "=")
c2 = InStr(d1, "&")
d2 = Mid(d1, c2 + 1)
d3 = Mid(d1, c1 + 1, (c2 - c1) - 1) 'value of Dept is d3
c3 = InStr(d2, "=")
c4 = InStr(d2, "&")
d5 = Mid(d2, c4 + 1)
d4 = Mid(d2, c3 + 1, (c4 - c3) - 1) 'value of Queue is d4
c6 = InStr(d5, "=")
d6 = Mid(d5, c6 + 1) ' Value of Day is d6
Hope this helps
Related
I have been trying to write some VBA in Excel to transpose a 2D list, based on searching for the first character "{".
Before:
After:
My code:
With Sheets("Results").Range(Cell1:="A1", Cell2:="A39")
Set a = .Find("{", After:=Range("A" & lRow))
Set b = a
c = a.Address
Do While Not .FindNext(b) Is Nothing And a.Address <> .FindNext(b).Address
c = c & "," & .FindNext(b).Address
rangeToMoveCell1 = a.Address
rangeToMoveCell2 = .FindNext(b).Address
MsgBox ("rangeToMoveCell1: " & rangeToMoveCell1 & vbNewLine & "rangeToMoveCell2: " & rangeToMoveCell2)
Sheets("Results").Range(Cell1:=rangeToMoveCell1, Cell2:=rangeToMoveCell2).Copy
Sheets("Results").Range(Cell1:=rangeToMoveCell1, Cell2:=rangeToMoveCell2).Offset(-3, 1).PasteSpecial Transpose:=True
Sheets("Results").Range(Cell1:=rangeToMoveCell1, Cell2:=rangeToMoveCell2).Clear
Set b = .FindNext(b)
Loop
End With
I've come up with this and it works, except it does not process the last find:
With Sheets("Results").Range(Cell1:="A1", Cell2:="A" & lRow)
Set a = .Find("{", After:=Range("B" & lRow))
Set b = a
c = a.Offset(3).Address
Do While Not .FindNext(b) Is Nothing And a.Address <> .FindNext(b).Address
Set nextFind = .FindNext(b)
Set d = nextFind
'MsgBox ("d: " & d)
e = nextFind.Offset(-1, 1).Address
Sheets("Results").Range(Cell1:=c, Cell2:=e).Copy
Sheets("Results").Range(Cell1:=c, Cell2:=e).Offset(-3, 2).PasteSpecial Transpose:=True
Sheets("Results").Range(Cell1:=c, Cell2:=e).EntireRow.Delete
Sheets("Results").Range(c).EntireRow.Insert
Sheets("Results").Range(c).EntireRow.Insert
c = nextFind.Offset(3).Address
Set b = .FindNext(b)
Loop
End With
Getting the following error....
<The expression you entered as a query parameter produced this error: 'rs!StoreID'>
rs!StoreID is an integer in the Stores table and prints out just fine in the msgbox function
What am I doing wrong? I've used Dcount many times before, just not in a loop through the records in a table...
Thanks!
strSQL = "SELECT * FROM Stores"
Set rs = CurrentDb.OpenRecordset(strSQL)
If Not rs.BOF And Not rs.EOF Then
rs.MoveFirst
While (Not rs.EOF)
MsgBox ("Store: " & rs!StoreID & ", Name: " & rs!FullStoreName)
'Make sure data exists for Store in AccountBalances Table for start and end dates
If ((DCount("*", "AccountBalances", "[RecDate] = TempVars!varDate And [StoreID] = rs!StoreID") <= 0) Or _
(DCount("*", "AccountBalances", "[RecDate] = TempVars!varStartDate And [StoreID] = rs!StoreID") <= 0)) Then
NoData = NoData + 1
NoDataStoreList = NoDataStoreList & rs!FullStoreName & vbCrLf
End If
MsgBox ("Checking for CFS Orphans")
'Check if any Account Numbers for selected Store have Unassigned CFS Line Item in the AccountNumbers Table
NumRecs = DCount("*", "AccountNumbers", "[StoreID] = rs!StoreID And [CFS LineItem] = 0 And [Account Type] = '2-Assets'") _
+ DCount("*", "AccountNumbers", "[StoreID] = rs!StoreID And [CFS LineItem] = 0 And [Account Type] = '3-Liability'") _
+ DCount("*", "AccountNumbers", "[StoreID] = rs!StoreID And [CFS LineItem] = 0 And [Account Type] = '4-Net Worth'")
If (NumRecs > 0) Then
CFSOrphans = CFSOrphans + 1
CFSOrphansStoreList = CFSOrphansStoreList & rs!FullStoreName & " - " & NumRecs & " Accounts" & vbCrLf
End If
rs.MoveNext
Wend
End If
rs.Close
Set rs = Nothing
The values must be concatenated, for example:
If ((DCount("*", "AccountBalances", "[RecDate] = TempVars!varDate And [StoreID] = " & rs!StoreID & "") <= 0) Or _
(DCount("*", "AccountBalances", "[RecDate] = TempVars!varStartDate And [StoreID] = " & rs!StoreID & "") <= 0)) Then
(I started learning about arrays today.) Edit: I realized the = is apperently causing the error because it's seen as a "compare if equal" vs "assign this".
i don't see which part in the referenced line is causing the error:
'Option 1
Var citylistDE(5) as string
citylistDE(0) ="Genf"
citylistDE(1)="Lausanne"
citylistDE(2)="Bern"
citylistDE(3)="Basel"
citylistDE(4)="Zürich"
citylistDE(5)="St.Gallen"
dim countDe as Integer = citylistDE.LastRowIndex
for i as integer = 0 to countDe
de.Value = de.Value = citylistDE(i) + EndOfLine '<=== THIS LINE ?
next
'Option2
var citylistFR() as string = array("Genève", "Lausanne", "Berne", "Bale", "Zurich", "Sant-Gall")
dim countFR as integer = citylistFR.LastRowIndex
for i as integer = 0 to countFR
fr.Value = fr.Value + citylistFR(i) + EndOFLine
next
i found the error. It was the = between de.Value and citylistDE.
I changed it from = to +.
de.Value = de.Value = citylistDE(i) + EndOfLine
next
to
de.Value = de.Value + citylistDE(i) + EndOfLine
next
Trying to allow a concatenated table to be referenced as such:
local group = table.concat(arguments, ",", 1)
where arguments = {"1,1,1"}
Currently, doing group[2] gives me the comma. How do I avoid that while still allowing for two-digit numbers?
(snippet of what I'm trying to use it for)
for i = 1, #group do
target:SetGroup(i, tonumber(group[i]))
end
Maybe you want something like
local i = 1
for v in string.gmatch(s, "(%w+),*") do
group[i] = v
i = i + 1
end
Revised version in response to comment, avoiding the table altogether:
local i = 1
for v in string.gmatch(s, "(%w+),*") do
target:SetGroup(i, tonumber(v))
i = i + 1
end
split function (you have to add it to code)
split = function(str, delim)
if not delim then
delim = " "
end
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
end
-- Handle the last field
result[nb + 1] = string.sub(str, lastPos)
return result
end
so
local arguments = {"1,1,1"};
local group = split(arguments[1], ",");
for i = 1, #group do
target:SetGroup(i, tonumber(group[i]))
end
also note that
local arguments = {"1,1,1"};
local group = split(arguments[1], ",");
local group_count = #group;
for i = 1, group_count do
target:SetGroup(i, tonumber(group[i]))
end
is faster code ;)
I just need to decode a URL, for example, replace %2E with .
I can hack out a method if one isn't build in, but my assumption is that there must be a URL decoding tool already existing.
Here's a snippet I wrote years ago
-markus
Public Function URLDecode(sEncodedURL As String) As String
On Error GoTo Catch
Dim iLoop As Integer
Dim sRtn As String
Dim sTmp As String
If Len(sEncodedURL) > 0 Then
' Loop through each char
For iLoop = 1 To Len(sEncodedURL)
sTmp = Mid(sEncodedURL, iLoop, 1)
sTmp = Replace(sTmp, "+", " ")
' If char is % then get next two chars
' and convert from HEX to decimal
If sTmp = "%" and LEN(sEncodedURL) + 1 > iLoop + 2 Then
sTmp = Mid(sEncodedURL, iLoop + 1, 2)
sTmp = Chr(CDec("&H" & sTmp))
' Increment loop by 2
iLoop = iLoop + 2
End If
sRtn = sRtn & sTmp
Next
URLDecode = sRtn
End If
Finally:
Exit Function
Catch:
URLDecode = ""
Resume Finally
End Function
No.
But here's one: URL Encoder and Decoder for VB
Or something along the lines of (possibly not complete):
Public Function URLDecode(ByVal strEncodedURL As String) As String
Dim str As String
str = strEncodedURL
If Len(str) > 0 Then
str = Replace(str, "&", " & ")
str = Replace(str, "", Chr(39))
str = Replace(str, "&quo", Chr(34))
str = Replace(str, "+", " ")
str = Replace(str, "%2A", "*")
str = Replace(str, "%40", "#")
str = Replace(str, "%2D", "-")
str = Replace(str, "%5F", "_")
str = Replace(str, "%2B", "+")
str = Replace(str, "%2E", ".")
str = Replace(str, "%2F", "/")
URLDecode = str
End If
End Function
Also, take a look at How can I URL encode a string in Excel VBA?
EncodeURL and DecodeURL function using htmlfile object(Late binding)
I got this source from this site: http://cocosoft.kr/442
Function ENCODEURL(varText As Variant, Optional blnEncode = True)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
With objHtmlfile.parentWindow
.execScript "function encode(s) {return encodeURIComponent(s)}", "jscript"
End With
End If
If blnEncode Then
ENCODEURL = objHtmlfile.parentWindow.encode(varText)
End If
End Function
Function DECODEURL(varText As Variant, Optional blnEncode = True)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
With objHtmlfile.parentWindow
.execScript "function decode(s) {return decodeURIComponent(s)}", "jscript"
End With
End If
If blnEncode Then
DECODEURL = objHtmlfile.parentWindow.decode(varText)
End If
End Function
For example,
str = ENCODEURL("/?&=") 'returns "%2F%3F%26%3D"
str = DECODEURL("%2F%3F%26%3D") 'returns "/?&="
Here is the code from the URL posted in another answer in case it goes down as it works great.
http://www.freevbcode.com/ShowCode.asp?ID=1512
Public Function URLEncode(StringToEncode As String, Optional _
UsePlusRatherThanHexForSpace As Boolean = False) As String
Dim TempAns As String
Dim CurChr As Integer
CurChr = 1
Do Until CurChr - 1 = Len(StringToEncode)
Select Case Asc(Mid(StringToEncode, CurChr, 1))
Case 48 To 57, 65 To 90, 97 To 122
TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
Case 32
If UsePlusRatherThanHexForSpace = True Then
TempAns = TempAns & "+"
Else
TempAns = TempAns & "%" & Hex(32)
End If
Case Else
TempAns = TempAns & "%" & _
Format(Hex(Asc(Mid(StringToEncode, _
CurChr, 1))), "00")
End Select
CurChr = CurChr + 1
Loop
URLEncode = TempAns
End Function
Public Function URLDecode(StringToDecode As String) As String
Dim TempAns As String
Dim CurChr As Integer
CurChr = 1
Do Until CurChr - 1 = Len(StringToDecode)
Select Case Mid(StringToDecode, CurChr, 1)
Case "+"
TempAns = TempAns & " "
Case "%"
TempAns = TempAns & Chr(Val("&h" & _
Mid(StringToDecode, CurChr + 1, 2)))
CurChr = CurChr + 2
Case Else
TempAns = TempAns & Mid(StringToDecode, CurChr, 1)
End Select
CurChr = CurChr + 1
Loop
URLDecode = TempAns
End Function
' URLDecode function in Perl for reference
' both VB and Perl versions must return same
'
' sub urldecode{
' local($val)=#_;
' $val=~s/\+/ /g;
' $val=~s/%([0-9A-H]{2})/pack('C',hex($1))/ge;
' return $val;
' }