1
votes

The following code was posted by Justin Dearing here: url checker VBA, when redirected, show redirected url

However, how on earth can I call this function to return T/F AND the target? I've tried various ways (Call, straight request etc) and continue to get compile errors, invalid use of object.

If I cut the function down to: Public Function GetResult(strUrl As String) As Boolean

This returns the T/F for a 301 or 302 however doesn't return the target.

What is the correct approach to calling this function to get the isRedirect True/False AND the target redirected too? What am I missing?

Any pointers appreciated. B

Public Function GetResult(ByVal strUrl As String, Optional ByRef isRedirect As Boolean, Optional ByRef target As String) As String
Dim oHttp As New WinHttp.WinHttpRequest

oHttp.Option(WinHttpRequestOption_EnableRedirects) = False
oHttp.Open "HEAD", strUrl, False
oHttp.send
GetResult = oHttp.Status & " " & oHttp.statusText
If oHttp.Status = 301 Or oHttp.Status = 302 Then
    isRedirect = True
    target = oHttp.getResponseHeader("Location")
Else
    isRedirect = False
    target = Nothing
End If
End Function
1
Amend the function to return an Array (As Variant) , dim the array to hold 2 items inside of the function , and have the array populated with the isRedirect and target before the end of the Function?QHarr

1 Answers

1
votes

Try this, see if this works.

Option explicit

Public Function GetResult(ByVal strUrl As String, Optional ByRef isRedirect As Boolean, Optional ByRef target As String) As String
Dim oHttp As WinHttp.WinHttpRequest
Set oHttp = new winhttp.winhttprequest

With ohttp
.Option(WinHttpRequestOption_EnableRedirects) = False
.Open "HEAD", strUrl, False
.send

GetResult = .Status & " " & .statusText

If .Status = 301 Or .Status = 302 Then
isRedirect = True
target = .getResponseHeader("Location")
Else 
isRedirect = False 
target = vbnullstring
End If 

End with

End Function

Untested and written on mobile, sorry for bad formatting.

Note that I don't use Dim ... As new syntax. Instead I use dim and set.

Hope it works. Let me know how you get on.

My understanding is that you want the function to return multiple values. Passing parameters ByRef is one workaround to achieve this. An alternative might be to return a single delimited string, which you then split() on the chosen delimiter. Or returning a variant.