Excel vba copy hyperlink

Hi all,
I’ve been working on this macro for days and I’m hoping someone can help me.  I’m using Excel 2007.

I have an existing workbook — let’s call it «WB1».  WB1 has hyperlinks in column «C» that have the «Text to Display» shown in the cell with the actual URL not shown.  So «C» would be something like «Click this link» and when they click it
it would go to the URL specified when the hyperlink was created.  Note that column C on WB1 has been merged with other columns. 

The workbook I’m creating is «WB2».  If I do a copy/paste in my macro from cell C in WB1 to WB2 the result is also a merged cell on WB2.  This would be OK, except that I then want to do some formatting, which can’t be done on merged cells.

So — what I want to do is use «hyperlinks.add» using the Anchor, Address, etc to get the hyperlink (including «text to display») from WB1 to WB2.  This will allow me to get the cell from WB1 to WB2 without ending up with a merged cell in WB2.  
I could easily do this if I wanted to copy a URL from one workbook to another, but in this instance I want the URL and the Text to Display on WB2.

The problem I’m having is I don’t know how to get the values for «text to display» and the «actual URL» out of the cell in WB1.  

Can anyone shed some light on this.  I’d really appreciate it.

BTW — I don’t have any control over WB1 — it comes to me that way.


KW

  • Edited by

    Friday, January 27, 2012 2:15 AM

 

Всем доброго здоровья!
Собираю некоторые данные на в таблицу на листе. Делаю это через массивы, т.к. конечный результат буде примерно 30 столбцов и до 10 000 строк.
Но в каждой строке должна быть гиперссылка типа

Планета Excel

Перенести гиперссылку довольно легко обычным Copy, но тогда я не смогу работать массивом; придется все делать на листе — а это очень долго.
Вопрос: как скопировать гиперссылку через массив?
Или, как в VBA «прочитать» гиперссылку, т.е. получить отдельно текст и адрес?

 

Sanja

Пользователь

Сообщений: 14838
Регистрация: 10.01.2013

#2

01.07.2017 12:29:48

Цитата
Михаил С. написал:
как в VBA «прочитать» гиперссылку, т.е. получить отдельно текст и адрес?

Ну для одной ячейки можно так

Код
    With Sheets(1).Range("B1").Hyperlinks(1)
        MsgBox "Адрес: " & .Address & vbCrLf & "Текст: " & .TextToDisplay
    End With

А вот как получить это в массив без перебора ячеек — вопрос..

Согласие есть продукт при полном непротивлении сторон.

 

Sanja, спасибо, подумаю над этим вариантом.
Перебрать оден столбец все таки быстрее, чем по ячейкам проходить два листа.

 

Sanja

Пользователь

Сообщений: 14838
Регистрация: 10.01.2013

#4

01.07.2017 12:36:57

Почитал тут справку. И т.к. HyperLinks это КОЛЛЕКЦИЯ, то с ней можно работать отдельно от ячеек. Например так

Код
    With Sheets(1)
        Arr1 = .Range("A1:A3").Value
        ReDim Arr2(.Range("B1:B3").Hyperlinks.Count-1)
        For Each hl In .Range("B1:B3").Hyperlinks
            Arr2(I) = hl.Address
            I = I + 1
        Next
    End With

Изменено: Sanja01.07.2017 12:42:45

Согласие есть продукт при полном непротивлении сторон.

 

Sanja

Пользователь

Сообщений: 14838
Регистрация: 10.01.2013

#5

01.07.2017 13:59:59

Михаил, как-то так получилось. Не знаю, насколько быстро будет на больших объёмах

Код
Sub HiperCopy()
Dim hlRange As Range
Dim Arr(), I&, lRow&
Dim hl As Hyperlink
With Sheets(1)
    lRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    ReDim Arr(0 To 3, 0 To .Range("B1:B" & lRow).Hyperlinks.Count - 1)
    For Each hl In .Range("B1:B" & lRow).Hyperlinks
        Arr(0, I) = hl.Parent.Offset(, -1).Value
        Arr(1, I) = hl.TextToDisplay
        Arr(2, I) = hl.Parent.Address
        Arr(3, I) = hl.Address
        I = I + 1
    Next
End With
I = 0
With Sheets(2)
    lRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    .Range("A1:A" & lRow).Resize(UBound(Arr, 2) + 1, 1) = Application.Transpose(Arr)
    For I = 0 To UBound(Arr, 2)
        .Range(Arr(2, I)).Hyperlinks.Add Anchor:=.Range(Arr(2, I)), Address:=Arr(3, I), TextToDisplay:=Arr(1, I)
    Next
End With
End Sub

Прикрепленные файлы

  • VBA копирование гиперссылки.xlsm (19.58 КБ)

Согласие есть продукт при полном непротивлении сторон.

 

Sanja, Ок, спасибо, попробую.

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#7

01.07.2017 20:48:43

Немного поигрался. Количество гиперсылок — max возможное (65530 шт).

Код
Sub qq()
    Dim t!
    t = Timer
    With Worksheets(3)
        For I = 1 To 65530
            .Hyperlinks.Add .Cells(I, 1), "http://example.microsoft.com"
        Next
    End With
    Debug.Print Format(Timer - t, "0.0000")
End Sub

отрабатывает 40-50сек

Код
Sub q()
    Dim ar
    Dim t!
    t = Timer
    With Worksheets(3)
        ar = .Range("a1:a65530").Value
        ReDim Preserve ar(1 To UBound(ar), 1 To 2)
        For I = 1 To UBound(ar)
            ar(I, 2) = .Cells(I, 1).Hyperlinks(1).Address
            If I Mod 1000 Then DoEvents
        Next
        Debug.Print Format(Timer - t, "0.0000")
        .Range("a1:a65530").Clear
        .Cells(I, 3).Resize(UBound(ar)) = ar
        For I = 1 To UBound(ar)
            .Hyperlinks.Add .Cells(I, 3), ar(I, 2)
            If I Mod 1000 Then DoEvents
        Next
    End With
    Debug.Print Format(Timer - t, "0.0000")
End Sub

1,5 минуты читает, 1,5 минуты пишет
Код Sanja,  из #5 4 сек читает, 6 минут пишет

Изменено: RAN01.07.2017 20:49:12

Предположим, у меня есть список значений в столбце A, и каждая ячейка содержит другую гиперссылку, теперь я хочу скопировать только гиперссылки без текста в другой столбец E, как показано на следующем снимке экрана. Возможно, нет прямого способа решить эту задачу в Excel, но здесь я могу ввести код VBA для решения этой проблемы.

док скопировать гиперссылку в другую ячейку 1

Скопируйте гиперссылку из одной ячейки в другую с кодом VBA


стрелка синий правый пузырь Скопируйте гиперссылку из одной ячейки в другую с кодом VBA

Чтобы скопировать только адреса гиперссылок без текста в другие ячейки, следующий код может оказать вам услугу, например:

1. Удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модулии вставьте следующий код в Модули Окно.

Код VBA: копировать гиперссылку только из одной ячейки в другую:

Sub CopyHyperlinks()
'Uodateby Extendoffice
    Dim xSRg As Range
    Dim xDRg As Range
    Dim I As Integer
    Dim xAddress As String
    On Error Resume Next
    xAddress = ActiveWindow.RangeSelection.Address
    Set xSRg = Application.InputBox("Please select the original range you want to copy hyperlinks:", "KuTools For Excel", xAddress, , , , , 8)
    If xSRg Is Nothing Then Exit Sub
    Set xDRg = Application.InputBox("Please select the new range you want to paste the hyperlinks only", "KuTools For Excel", , , , , , 8)
    If xDRg Is Nothing Then Exit Sub
    Set xDRg = xDRg(1)
    For I = 1 To xSRg.Count
        If xSRg(I) <> "" And xDRg.Offset(I - 1) <> "" Then
            If xSRg(I).Hyperlinks.Count = 1 Then
                xDRg(I).Hyperlinks.Add xDRg(I), xSRg(I).Hyperlinks(1).Address
            End If
        End If
    Next
End Sub

3, Затем нажмите F5 нажмите клавишу для запуска этого кода, появится диалоговое окно, напоминающее вам о выборе ячеек, в которые вы хотите скопировать только гиперссылки, см. снимок экрана:

док скопировать гиперссылку в другую ячейку 02

4, Затем нажмите OK, затем выберите ячейки, в которые вы хотите вставить гиперссылки, только в другое диалоговое окно, см. снимок экрана:

док скопировать гиперссылку в другую ячейку 03

5. И адреса гиперссылок были скопированы из исходных ячеек в указанные ячейки по мере необходимости, см. Снимок экрана:

док скопировать гиперссылку в другую ячейку 04

Внимание: Этот код также может помочь вам скопировать гиперссылки с одного листа на другой по вашему желанию.


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (13)


Оценок пока нет. Оцените первым!

  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

  1. Oct 3rd, 2006, 04:14 PM


    #1

    Webtest is offline

    Thread Starter


    Frenzied Member


    Esteemed Forum Participants and Lurkers:
    ===============================
    Excel 2003 VBA

    I need a process (code) to copy Hyperlinks from a cell on one sheet to a specific related cell on another sheet while preserving the format of the target cell. The Target Cell may have any number of different background and border formats. For test, it can all be on the same sheet from one column to another.

    If I copy the source cell and paste it on the destination cell, it overwrites the destination cell format, but that appears to be the only way I can copy the link. There doesn’t seem to be any «Paste Special» to paste just the Hyperlink. Paste Special Values doesn’t work … paste special formulas doesn’t work … etc. ad nauseam.

    I tried to copy just the format from the TARGET cell and paste it on the Source cell so that I could then copy the identically formatted Source cell back on the Target cell, but when I paste the format, it crashes the Hyperlink, leaving only the link text.

    Is there any quick and dirty way to do this without having to save every format property of each target cell and then rewrite them all?

    Last edited by Webtest; Oct 4th, 2006 at 07:48 AM.

    Blessings in abundance,
    All the Best,
    & ENJOY!

    Art . . . . Carlisle, PA . . USA


  2. Oct 3rd, 2006, 05:09 PM


    #2

    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format ???

    What about the following:

    VB Code:

    1. Dim h as Hyperlink

    2. For each h in SourceRange

    3. MyWorkSheet.Hyperlinks.Add TargetRange, h.Address

    4. Next h

    It’s easy enough to adapt if you need the link moved.

    zaza


  3. Oct 4th, 2006, 07:40 AM


    #3

    Webtest is offline

    Thread Starter


    Frenzied Member


    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format ???

    Thsnks zaza … we are sooooo close! The «Hyperlinks» collection has to be added after the source range! Your suggestion does indeed copy just the hyperlink without affecting the destination cell formatting. However, in my case, the destination cell depends on the address of the source cell, and I can’t figure out the range address of each hyperlink cell «hLink». As you can see, I have tried everything I could find …

    Code:

    Option Explicit
    Sub junk()
        Dim aSheet As Worksheet
        Dim hLink As Hyperlink
        Dim i As Integer
        
        Set aSheet = ActiveWorkbook.Sheets("TEST")
        i = 1
        For Each hLink In aSheet.Range("B1:B18").Hyperlinks  'A simple test range ... real range is complex
            aSheet.Hyperlinks.Add aSheet.Cells(i, "D"), hLink.Address, , , cStr(hLink.Parent)
            
            Debug.Print hLink.Address 'This is the URL
            Debug.Print hLink.Parent  'This PRINTS the Link Text - Actually is the RANGE !!!
            Debug.Print hLink.Creator '??? a process handle?
            Debug.Print hLink.Range   'This is also the Link Text
            Debug.Print hLink.Type    '???
            
            i = i + 1
        Next hLink
    
    End Sub

    How can I find the ADDRESS of the elements of the Hyperlinks collection?

    Last edited by Webtest; Oct 4th, 2006 at 08:15 AM.

    Blessings in abundance,
    All the Best,
    & ENJOY!

    Art . . . . Carlisle, PA . . USA


  4. Oct 4th, 2006, 07:47 AM


    #4

    Webtest is offline

    Thread Starter


    Frenzied Member


    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format ???

    I got it … hLink.Range.Address

    Thanks zaza … you’re input was excellent … just what I needed! Your rating gets bumped up a notch!

    Blessings in abundance,
    All the Best,
    & ENJOY!

    Art . . . . Carlisle, PA . . USA


  5. Oct 4th, 2006, 08:12 AM


    #5

    Webtest is offline

    Thread Starter


    Frenzied Member


    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

    Here is the final working TEST code:

    Code:

    Option Explicit
    Sub HyperlinkMoveTest()
        Dim aSheet As Worksheet 'Sheet Handle
        Dim hLink As Hyperlink  'Hyperlink Handle
        Dim rngDst As Range     'Destination Cell
        Dim rngSrc As Range     'Source Cell
        
        'Set a Handle for the working Sheet
        Set aSheet = ActiveWorkbook.Sheets("TEST")
        'Iterate through all the Hyperlinks in a range
        For Each hLink In aSheet.Range("B1:B18").Hyperlinks
            'Fetch the cell address of the source Hyperlink
            Set rngSrc = hLink.Range
            'Set the Destination Cell address based on the Source Cell address
            Set rngDst = rngSrc.Offset(0, 2)
            'Load the Destination Cell with the Hyperlink WITHOUT AFFECTING THE FORMAT !!!
            aSheet.Hyperlinks.Add rngDst, hLink.Address, , , hLink.Range.Text
        Next hLink
    End Sub

    Thanks again, zaza

    Blessings in abundance,
    All the Best,
    & ENJOY!

    Art . . . . Carlisle, PA . . USA


  6. Jun 1st, 2010, 09:26 AM


    #6

    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

    can u helpm with my problem

    have the hyperlinks in a cell just tryin to put the hyperlink in the body of an email, can get text but want the link

    code is =

    Code:

    Sub NEWACTION()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim EmailAddr As String
    Dim Subj As String
    Dim BodyText As String
    Dim hLink As Hyperlink
    
    EmailAddr = Sheets(CurrentSheet).Cells(RowNumber, 9)
    Subj = " You Have Been Assigned Reponsibilty For the Following Action! "
    
    BodyText = " You have been assigned an Action of - " & Sheets(CurrentSheet).Cells(RowNumber, 5) & " - To Be Completed by - " & Sheets(CurrentSheet).Cells(RowNumber, 8) & vbCr & vbLf & vbCr & vbLf
    hLink = Sheets(CurrentSheet).Cells(RowNumber, 2).Hyperlinks
    BodyText = BodyText & hLink
    
    Set OutApp = CreateObject("Outlook.Application")
    OutApp.Session.Logon
    Set OutMail = OutApp.CreateItem(0)
    
    With OutMail
    .to = EmailAddr
    .BCC = ""
    .Subject = Subj
    .Body = BodyText
    '.Attachments.Add ActiveWorkbook.FullName
    .Display 'or use
    .send
    End With
    
    Set OutMail = Nothing
    Set OutApp = Nothing
    End Sub

    can u help its not pickin up the hyperlink ok cheers

    ————————————————
    «The hall is rented,»
    «the orchestra is engaged,»
    «its now time to see if you can dance!»
    Q, Q-Who, Star Trek The Next Generation
    ————————————————
    General Work day

    ————————————————
    DOS, Win 95, Win 98 SE, Win ME, Win NT 4.0 SP6a, Windows 2000 SP3, Window XP SP1, Windows 7, Windows 8/8.1, Windows 10, Office 97 Pro, Office 2000 Pro, Office 2010, Office 2013, Office 2016, Office 2019, Visual Basic 6 (SP5), SQL, Oracle


  7. Jun 1st, 2010, 02:32 PM


    #7

    Webtest is offline

    Thread Starter


    Frenzied Member


    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

    Robbo … (Is that an «Old Tanglefoot» in your personal icon?)

    It’s been awhile since I have had VBA open, and I have no experience with auto generating e-mails … but … and I’m just guessing here … if you want ‘funny’ stuff in an e-mail, don’t you have to format it in HTML? For that you’ll just need an href line …

    Code:

    To open the link in a new page:
    <A href="...url.goes.here..." target=_blank> link text </A>
    To open the link in the active page already open ...
    <A href="...url.goes.here..." target=_self> link text </A>

    The «target» specifier is optional. I think you can just plug in the extra canned HTML text strings around the URL text you fetch out of the cell and whatever you want for the Link Text. You’ve probably already figured this out?

    Hope this helps … let me know if you need more help or if I got lucky!
    Blessings in abundance, all the best, and ENJOY!
    Art in Carlisle PA USA

    Blessings in abundance,
    All the Best,
    & ENJOY!

    Art . . . . Carlisle, PA . . USA


  8. May 26th, 2011, 11:47 AM


    #8

    newguy91 is offline


    New Member


    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

    The code below is very similar to what I want to do with my excel file. I want to copy just the hyperlinks from a 200 row, 2 column selection and place them in the same place in a different sheet. Can anyone help me out? I’ve never done this before and also need help with how to rename the stuff so that it works for my files. (such as the Set aSheet line)

    Option Explicit
    Sub HyperlinkMoveTest()
    Dim aSheet As Worksheet ‘Sheet Handle
    Dim hLink As Hyperlink ‘Hyperlink Handle
    Dim rngDst As Range ‘Destination Cell
    Dim rngSrc As Range ‘Source Cell

    ‘Set a Handle for the working Sheet
    Set aSheet = ActiveWorkbook.Sheets(«TEST»)
    ‘Iterate through all the Hyperlinks in a range
    For Each hLink In aSheet.Range(«B1:B18»).Hyperlinks
    ‘Fetch the cell address of the source Hyperlink
    Set rngSrc = hLink.Range
    ‘Set the Destination Cell address based on the Source Cell address
    Set rngDst = rngSrc.Offset(0, 2)
    ‘Load the Destination Cell with the Hyperlink WITHOUT AFFECTING THE FORMAT !!!
    aSheet.Hyperlinks.Add rngDst, hLink.Address, , , hLink.Range.Text
    Next hLink
    End Sub


  9. Sep 7th, 2011, 10:35 AM


    #9

    vela0026 is offline


    New Member


    Smile Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

    Thank you. The code worked great. This is my final code. Takes the list of companies in column A and moves the actual hyperlink to column C.

    Sub HyperlinkMoveTest()
    Dim aSheet As Worksheet ‘Sheet Handle
    Dim hLink As Hyperlink ‘Hyperlink Handle
    Dim rngDst As Range ‘Destination Cell
    Dim rngSrc As Range ‘Source Cell

    ‘Set a Handle for the working Sheet
    Set aSheet = ActiveWorkbook.Sheets(«TEST»)
    ‘Iterate through all the Hyperlinks in a range
    For Each hLink In aSheet.Range(«A1:A193»).Hyperlinks
    ‘Fetch the cell address of the source Hyperlink
    Set rngSrc = hLink.Range
    ‘Set the Destination Cell address based on the Source Cell address
    Set rngDst = rngSrc.Offset(0, 2)
    ‘Load the Destination Cell with the Hyperlink WITHOUT AFFECTING THE FORMAT !!!
    aSheet.Hyperlinks.Add rngDst, hLink.Address
    Next hLink
    End Sub


  10. Aug 25th, 2012, 10:19 PM


    #10

    la.wells is offline


    New Member


    Exclamation Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

    This is exactly what I was looking for and it works except for one issue. It copies my hyperlinks to the next column but I have a DrillDown Sub Selection.ShowDetail = True. My hyperlinks point other sheets in the workbook that have pivot tables. I wanted the users to be able to click on the hyperlink and see the detail behind the pivot cell it was pointing to instead of the summed total. This code does not copy the DrillDown Sub part. I apologize in advance but I don’t know how to easily add that back in. Below is your code that I tweaked to work with my workbook:

    Sub HyperlinkMoveTest()
    Dim aSheet As Worksheet ‘Sheet Handle
    Dim hLink As Hyperlink ‘Hyperlink Handle
    Dim rngDst As Range ‘Destination Cell
    Dim rngSrc As Range ‘Source Cell

    ‘Set a Handle for the working Sheet
    Set aSheet = ActiveWorkbook.Sheets(«Trending»)
    ‘Iterate through all the Hyperlinks in a range
    For Each hLink In Selection.Hyperlinks
    ‘Fetch the cell address of the source Hyperlink
    Set rngSrc = hLink.Range
    ‘Set the Destination Cell address based on the Source Cell address
    Set rngDst = rngSrc.Offset(0, 1)
    ‘Load the Destination Cell with the Hyperlink WITHOUT AFFECTING THE FORMAT !!!
    aSheet.Hyperlinks.Add rngDst, hLink.Address, hLink.Range.Text
    Next hLink
    End Sub

    Thank you in advance.


  11. Aug 29th, 2012, 07:42 AM


    #11

    naveeanr is offline


    New Member


    Re: EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]

    This is related to the problem i have in the excel, the task is to copy the hyperlink data from a particular column in Excel and when i click a Macro button it should automatically
    fetch the data from that particular column of Excel. Can anyone sugget me solution…?


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • EXCEL VBA: How To: Copy Hyperlink while Preserving Target Format [RESOLVED]


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

RoryA

RoryA

MrExcel MVP, Moderator


  • #2

That code doesn’t actually do anything. Can you post the code that actually transfers the cells?

  • #3

That code doesn’t actually do anything. Can you post the code that actually transfers the cells?

Apologies, here’ the full code:

Code:

    Dim Sh As Worksheet
    Dim Newsh As Worksheet
    Dim myCell As Range
    Dim ColNum As Integer
    Dim RwNum As Long
    Dim Basebook As Workbook
   
    Set Basebook = ThisWorkbook
    Set Newsh = Basebook.Worksheets("Orders")
    Newsh.Rows("5:" & Newsh.Rows.Count).Clear
        
'The links to the first sheet will start in row 2
    RwNum = 3
    For Each Sh In Basebook.Worksheets
    If Sh.Name <> Newsh.Name And Sh.Visible Then
    ColNum = 1
    RwNum = RwNum + 1
            
'Create a link to the sheet in the A column
    Newsh.Hyperlinks.Add Anchor:=Newsh.Cells(RwNum, 1), Address:="", _
    SubAddress:="'" & Sh.Name & "'!A1", TextToDisplay:=Sh.Name
                            
    For Each myCell In Sh.Range("J9,D9,D13,O66,D8,A1")
    
    
    ColNum = ColNum + 1
    Newsh.Cells(RwNum, ColNum).Formula = _
    "='" & Sh.Name & "'!" & myCell.Address(False, False)
                
        Next myCell
            
            End If
        
    Next Sh

What basically happens, as you can probably tell from the code, a sheet called Orders is created and pulls info from the cells («J9,D9,D13,O66,D8,A1») from all other sheets created.

Last edited by a moderator: Dec 19, 2016

RoryA

RoryA

MrExcel MVP, Moderator


  • #4

You can’t return a hyperlink like that. Would it be OK to simply copy that cell across directly, or do you actually need the two cells linked?

  • #5

You can’t return a hyperlink like that. Would it be OK to simply copy that cell across directly, or do you actually need the two cells linked?

Ideally they need to be linked… the Orders sheet links to the cells J9,D9,D13,O66,D8,A1 from all other created sheets automatically. Users can access the link from the other sheets, the Orders sheet just collates certain cells creating a list with the most important data and cell A1 is a hyperlink to a PDF attachment.

If it can’t be done, I’ll just have to re think the hyperlink scenario.

Thanks for your time…

Steven.

RoryA

RoryA

MrExcel MVP, Moderator


  • #6

What exactly is in A1 on the source sheet? If it’s the path to the file, you could use a HYPERLINK formula to create the link in the new sheet.

  • #7

What exactly is in A1 on the source sheet? If it’s the path to the file, you could use a HYPERLINK formula to create the link in the new sheet.

Yes, that’s exactly what A1 is, it’s a user created Hyperlink to a PDF file on the Server. The current code just doesn’t copy the Hyperlink across.

RoryA

RoryA

MrExcel MVP, Moderator


  • #8

Does the displayed text include the file path, or just the file name?

  • #9

Does the displayed text include the file path, or just the file name?

Just the file name…

RoryA

RoryA

MrExcel MVP, Moderator


  • #10

Then you’ll need a UDF in the file to extract the actual path of the hyperlink. So you could add this:

Code:

Function HLinkPath(Cell As Range) As String
    On Error Resume Next
    HLinkPath = Cell(1).Hyperlinks(1).Address
End Function

to your module. Then alter your current code to this:

Code:

    For Each myCell In Sh.Range("J9,D9,D13,O66,D8,A1")
    
    
    ColNum = ColNum + 1
    if mycell.address(0,0) = "A1" then
Newsh.Cells(RwNum, ColNum).Formula = _
    "=HYPERLINK(HLinkPath('" & Sh.Name & "'!" & myCell.Address(False, False) & "))
    else
    Newsh.Cells(RwNum, ColNum).Formula = _
    "='" & Sh.Name & "'!" & myCell.Address(False, False)
    end if       
        Next myCell

Like this post? Please share to your friends:
  • Excel vba copy cell and paste
  • Excel vba copy all sheets to one sheet
  • Excel vba convert to string
  • Excel vba control type
  • Excel vba const array