+ Reply to Thread
Results 1 to 16 of 16

VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Question VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Hi all,

    I found this code which gives you the full URL of a shortened (e.g. bitly) link:

    Public Function unwrap(url As String) As String
        
        Static oRequest As Object
        
        Set oRequest = CreateObject("WinHTTP.WinHTTPRequest.5.1")
        
        With oRequest
            .Option(6) = True
            .Option(12) = True
            .Open "HEAD", url, False
            .send
            unwrap = .Option(1)
        End With
        
    End Function
    You basically use this on a cell by cell basis via =unwrap(A1) formula.

    I have a fixed range of shortened URLs (that change dynamically) that I would like to get unwrapped one by one, but only at the click of a button. So ideally, this wouldn't be a public function, but a simple sub that I can manually execute on a specified range of cells.
    Anyone has an idea how to do that? Tried a few things, but totally lost :-(

    Hope you can help?
    Thanks!

  2. #2
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2405-17628.20102
    Posts
    1,420

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    You could use the same function in a range loop, something like the below, sub 'test' will run unwrap over and over until the end of the range:
    Sub test()
        Dim rng As Range, rCell As Range
        
        rng = Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
        
        For Each rCell In rng.Cells
            rCell.Offset(, 1) = unwrap(rCell.Value)
        Next rCell
    End Sub
    
    Public Function unwrap(url As String) As String
        Static oRequest As Object
        Set oRequest = CreateObject("WinHTTP.WinHTTPRequest.5.1")
        With oRequest
            .Option(6) = True
            .Option(12) = True
            .Open "HEAD", url, False
            .send
            unwrap = .Option(1)
        End With
    End Function
    If things don't change they stay the same

  3. #3
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Hey CheeseSandwich,

    Ace - thanks for the super speed reply!

    So I added the worksheet to look at as well and updated the range, but sadly, this throws an error on the "rng = " row: Run-time error '91': Object variable or With block variable not set

    Do you know what that means?

    Sub Unwrapper()
        Dim rng As Range, rCell As Range
        
        
        rng = Worksheets("Content_Audit").Range("H9:H" & Range("H" & Rows.Count).End(xlUp).Row)
        
        For Each rCell In rng.Cells
            rCell.Offset(, 1) = Unwrap(rCell.Value)
        Next rCell
    End Sub
    
    Public Function Unwrap(url As String) As String
        Static oRequest As Object
        Set oRequest = CreateObject("WinHTTP.WinHTTPRequest.5.1")
        With oRequest
            .Option(6) = True
            .Option(12) = True
            .Open "HEAD", url, False
            .send
            Unwrap = .Option(1)
        End With
    End Function
    Also, I just noticed that the cells in range H9:H contain a formula that outputs the shortened URL.
    Tried the previous =unwrap(A1) on those and it didn't work as I believe it reads the formula, not the output. Is there any tweak to that I could incorporate?

    Thanks so much for the help!
    Cheers!

  4. #4
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2405-17628.20102
    Posts
    1,420

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Sorry my mistake - I missed the word Set:
    Set rng = Worksheets("Content_Audit").Range("H9:H" & Range("H" & Rows.Count).End(xlUp).Row)

  5. #5
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Great - thanks! That got it to work, but it sadly only copies the URL instead of 'unwrapping' it - I guess this is because the cells in column H contain a formula that outputs the URL.

    An example - this is the formula in cell H9:

    Formula: copy to clipboard

    =IFERROR(TRIM(CLEAN(MID(RawData!B2,SEARCH(TRIM(CLEAN(VLOOKUP(D9,Lookups!$C$208:$H$296,6,FALSE))), RawData!B2)+LEN(TRIM(CLEAN(VLOOKUP(D9,Lookups!$C$208:$H$296,6,FALSE))))+2,SEARCH(">",RawData!B2,SEARCH(TRIM(CLEAN(VLOOKUP(D9,Lookups!$C$208:$H$296,6,FALSE))),RawData!B2)+2)-SEARCH(TRIM(CLEAN(VLOOKUP(D9,Lookups!$C$208:$H$296,6,FALSE))),RawData!B2)-LEN(TRIM(CLEAN(VLOOKUP(D9,Lookups!$C$208:$H$296,6,FALSE))))-2))),"-")


    ...it basically searches a large text document for a specific, shortened bitly link.

    The output of this formula is "https://bit.ly/3b2vDXN".

    If I apply the =unwrap(A1) formula on just the URL, this works, however, it doesn't work on cell H9 as it contains the formula (I believe).
    Do you think there's any workaround for that? I.e. let VBA pick the value of the cell rather than the formula to run this?

    Also, some cells in my range H9: range are left empty as the IFERROR formula kicks in. The script seems to stop when there is an empty cell so I changed the output of the formula to be "-" instead of a blank so the script continues to run, but not sure if that would throw an error now as "-" is not a valid URL?

    Thanks so much for the help - appreciate it!!

  6. #6
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2405-17628.20102
    Posts
    1,420

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Are you able to paste a sample of your data with a couple of working formulae? (sensitive data removed, maybe you could just leave a couple of fake URL's created by the same formula)

    Would be a lot easier to work with.

    Do the links created by formulae work when you put them into a web browser URL?
    Last edited by CheeseSandwich; 06-15-2022 at 09:35 AM.

  7. #7
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Question Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Sure - attached, hope this works?

    One thing to notice is that it does seem to work on some URLs, but not on others (can't share those ones sadly). So I may need to look into all the options there are for "oRequest" - maybe I can tweak this to also recognize other, shortened URLs.

    Thanks so much for your help!
    Attached Files Attached Files

  8. #8
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2405-17628.20102
    Posts
    1,420

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    The below will fix the error with the blank (-) cells:
    Sub Unwrapper()
        Dim rng As Range, rCell As Range
        
        Set rng = Worksheets("Content_Audit").Range("H9:H" & Range("H" & Rows.Count).End(xlUp).Row)
        
        For Each rCell In rng.Cells
            If rCell.Value <> "-" Then
                rCell.Offset(, 1) = unwrap(rCell.Value)
            End If
        Next rCell
    End Sub
    To test the ones that are not working: try pasting the formula result into your browser - if you get an error then there could be something wrong with the shortened URL.

  9. #9
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Thank you!! That's super helpful - I tweaked it slightly to skip blank cells now (not the ones with "-").

    Sub Unwrapper()
        Dim rng As Range, rCell As Range
        
        Set rng = Worksheets("Content_Audit").Range("H9:H1008")
        
        For Each rCell In rng.Cells
            If rCell.Value <> "" Then
                rCell.Offset(, 1) = Unwrap(rCell.Value)
            End If
        Next rCell
    End Sub
    
    Public Function Unwrap(url As String) As String
        Static oRequest As Object
        Set oRequest = CreateObject("WinHTTP.WinHTTPRequest.5.1")
        With oRequest
            .Option(6) = True
            .Option(12) = True
            .Open "HEAD", url, False
            .send
            Unwrap = .Option(1)
        End With
    End Function
    Only problem that remains is that some wrapped URLs don't seem to work (they do work and redirect if I open in browser). The script just seems to copy/paste the same URL into column "I".
    Think this may be down to some redirect setting maybe. Are there other methods of unwrapping the URL? I'll see if I can find anything...

    Thanks so much!

  10. #10
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Ok, I think I found something - apparently (according to this), WinHTTP.WinHTTPRequest.5.1 only looks at the first Location header (not the last link in the chain of redirects).
    It is recommended to use something like this instead:

    Option Explicit
    
    Dim GetLocation
    Const SXH_OPTION_URL = -1
    
    Dim h
    Set h = CreateObject("MSXML2.ServerXMLHTTP")
        h.Open "HEAD", "http://google.com/", False 
        h.send
    GetLocation = h.getOption(SXH_OPTION_URL) 'final URL even if redirected
    
    MsgBox GetLocation
    Tried to just change WinHTTP.WinHTTPRequest.5.1 to MSXML2.ServerXMLHTTP, but that doesn't work. Any chance you could help me tweak the code to look at the last link in the chain of redirects?

    Thanks so much!

  11. #11
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2405-17628.20102
    Posts
    1,420

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Try the below:
    Sub Unwrapper()
        Dim rng As Range, rCell As Range
        
        Set rng = Worksheets("Content_Audit").Range("H9:H13")
        
        For Each rCell In rng.Cells
            If rCell.Value <> "" Then
                rCell.Offset(, 1) = Unwrap(rCell.Value)
            End If
        Next rCell
    End Sub
    
    Public Function Unwrap(url As String) As String
        Dim h As Object
        Set h = CreateObject("MSXML2.ServerXMLHTTP")
            h.Open "HEAD", url, False
            h.send
        Unwrap = h.getOption(-1) 'final URL even if redirected
    End Function

  12. #12
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Hey CheeseSandwich,

    Thanks so much for this! Tried, but sadly not giving me the final URL (it does for some, but not for all) :-(

    But - good news is - I found this awesome redirect checker script here that seems to do the job:

    Private Changing As Boolean
    
    Private Sub RedirectChecker(ByVal url As String)
        Dim sh As Worksheet
        Set sh = ActiveSheet
        
        Dim http As New WinHttp.WinHttpRequest
        http.Option(WinHttpRequestOption_UserAgentString) = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"
        http.Option(WinHttpRequestOption_EnableRedirects) = False
        
        '' Clear existing info
        sh.Cells(3, 3).Formula = ""
        sh.Cells(4, 3).Formula = ""
        DoEvents
        
        '' Add protocol if missing
        If (InStr(url, "://") = 0) Then
            url = "http://" & url
        End If
        
        '' Launch the HTTP request
        http.Open "GET", url
        If Err.Number <> 0 Then
            '' Handle URL formatting errors
            sh.Cells(3, 3).Formula = Trim(Err.Description)
            Exit Sub
        End If
        http.Send
        If Err.Number <> 0 Then
            '' Handle HTTP errors
            sh.Cells(3, 3).Formula = Trim(Err.Description)
            Exit Sub
        End If
        '' Show HTTP response info
        sh.Cells(3, 3).Formula = http.Status & " " & http.StatusText
        sh.Cells(4, 3).Formula = http.GetResponseHeader("Location")
    End Sub
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Changing Then Exit Sub
        Changing = True
        Dim Name As String
        On Error Resume Next
        Name = Target.Name.Name
        If Name = "URL" Then
            RedirectChecker Target.Value
        End If
        On Error GoTo 0
        Changing = False
    End Sub
    This works perfectly, however, sadly it only looks at 1 input URL, not a range. Not quite sure how I could tweak it to:

    a) look at range Worksheets("Content_Audit").Range("H9:H1008") and check status and final URL for each cell in that range
    b) write the Redirect Value into the cell to the right of the input URL (column I)
    c) write the final URL into the cell two cells to the right of the input URL (column J)
    d) Execute this on click, rather than automatically

    Do you have any idea? Think that would really be it (appreciate the support!).
    Attached Files Attached Files
    Last edited by kingofcamden; 06-16-2022 at 04:12 AM.

  13. #13
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2405-17628.20102
    Posts
    1,420

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Maybe something like:
    Sub Unwrapper()
        Dim rng As Range, rCell As Range, wsCA As Worksheet
        
        Set wsCA = Sheets("Content_Audit")
        With wsCA
            Set rng = .Range("H9:H" & .Range("H" & Rows.Count).End(xlUp).Row)
        End With
        
        For Each rCell In rng.Cells
            If rCell.Value <> "" Then
                rCell.Offset(, 1) = rCell.Value
                rCell.Offset(, 2) = unwrap(rCell.Value)
            End If
        Next rCell
    End Sub
    
    Function unwrap(url As String)
        Dim http As New WinHttp.WinHttpRequest
        
        http.Option(WinHttpRequestOption_UserAgentString) = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"
        http.Option(WinHttpRequestOption_EnableRedirects) = False
        http.Open "GET", url
        http.Send
        unwrap = http.GetResponseHeader("Location")
    End Function

  14. #14
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    Thanks for the super speedy reply! Tried this, but unfortunately get a "compile error: User-defined type not defined" on row "Function unwrap(url As String)".

    Is there also a chance too add in the redirect type in another column? The script I found does this nicely, but sadly only for that 1 URL :-(

  15. #15
    Forum Expert CheeseSandwich's Avatar
    Join Date
    12-22-2021
    Location
    Kent, England
    MS-Off Ver
    365 - 2405-17628.20102
    Posts
    1,420

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    For the error i think you need to add a reference in the VBE: Microsoft WinHTTP Services

    For the second part, try the below:
    Sub Unwrapper()
        Dim rng As Range, rCell As Range, wsCA As Worksheet, str As String
        
        Set wsCA = Sheets("Content_Audit")
        With wsCA
            Set rng = .Range("H9:H" & .Range("H" & Rows.Count).End(xlUp).Row)
        End With
        
        For Each rCell In rng.Cells
            If rCell.Value <> "" Then
                str = unwrap(rCell.Value)
                rCell.Offset(, 1) = Split(str, "|")(0)
                rCell.Offset(, 2) = Split(str, "|")(1)
            End If
        Next rCell
    End Sub
    
    Function unwrap(url As String)
        Dim http As New WinHttp.WinHttpRequest
        
        http.Option(WinHttpRequestOption_UserAgentString) = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"
        http.Option(WinHttpRequestOption_EnableRedirects) = False
        http.Open "GET", url
        http.Send
        unwrap = http.Status & " " & http.StatusText & "|" & http.GetResponseHeader("Location")
    End Function

  16. #16
    Forum Contributor
    Join Date
    08-25-2015
    Location
    London
    MS-Off Ver
    MS 365
    Posts
    215

    Re: VBA - Tweak code to 'unwrap' shortened URLs for specified range on click

    OMG! LIFESAVER! This works perfectly - thank you soooo much!!!

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. VBA to Click URLs Office 365
    By sburt09 in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 05-12-2020, 11:31 PM
  2. Can this code be shortened?
    By frankytheman in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 03-02-2020, 12:48 AM
  3. VBA Code to Open Multiple URLs in a Range
    By MichaelV in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 09-16-2019, 05:17 PM
  4. [SOLVED] Tweak code to copy range formatting too (instead of just copying values)
    By Andrew.Trevayne in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 02-04-2017, 03:01 AM
  5. Slight Tweak to Click and Drag
    By diggetybo in forum Excel Formulas & Functions
    Replies: 2
    Last Post: 10-21-2014, 05:57 AM
  6. Can this code be shortened?
    By zookeepertx in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 05-20-2014, 09:52 AM
  7. [SOLVED] macro to wrap/unwrap text for a given range
    By Gti182 in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 03-26-2014, 09:36 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1