Efficiently copy text from Excel to Word, hyperlink if applicable - vba

What I'm trying to do
I'm trying to copy contents of different Excel cells into their respective Word bookmarks. Then this filled-in Word document gets pasted into an Outlook email. If the cell has a URL in it, I want it to be a clickable hyperlink in the email.
The problem
If the cell's value was a URL, then while it was un-hyperlinked before sending the email, it appeared hyperlinked (for some people) when the email was received. However, others users saw what looked like a clickable link (blue and underlined), but were unable to click because it wasn't actually hyperlinked. My guess is that certain mail programs recognize the URL and automatically hyperlink it while others do not.
What I've tried
I figured the solution was to make sure the URL was hyperlinked before sending. I tried a few forms of .PasteSpecial and .PasteAndFormat with the URL already hyperlinked in Excel. I got close, but either got an unwanted carriage return or no hyperlink. My latest try is a 2-line hack:
'put the cell contents in (sans formatting)
BKMRange.Text = ActiveCell.Value
'If it looks like a hyperlink, then hyperlink it
If UCase(Left(ActiveCell.Value, 4)) = "HTTP" Or UCase(Left(ActiveCell.Value, 4)) = "WWW." Then TempEmailDoc.Hyperlinks.Add BKMRange, ActiveCell.Value
The problem with this is that if the cell is more than just a URL (e.g. "This is your URL: www.google.com"), the URL won't get hyperlinked, since the first 4 characters are not "HTTP" or "WWW.". I could do a more robust search for "HTTP" or "WWW.", but then the code becomes much more complicated. There must be a more efficient way.
My question
How can I efficiently copy cell contents, but preserve hyperlinks if the cell contains them?
Thanks!

You can use the cell's Hyperlinks collection to learn whther the cell contains a hyperlink:
Sub test()
Dim i
i = Selection.Hyperlinks.Count
If (i > 0) Then MsgBox Selection.Hyperlinks(1).Address
End Sub
Now that you know a cell is (contains) a hyperlink, you can insert it as a hyperlink in Outlook. I assume you work in Outlook VBA and open the worksheets in Outlook VBA.
Note that when you enter a proper URL in Excel it will turn it automaticlly into a hyperlink.

Related

Combining Rich Text Content Control Content in MS Word using VBA

I'm trying to create a form for a non-technical user in MS Word to capture some text content in MS Word. This word doc consists of several rich text content controls where the user will type in or paste in some formatted data (bold, underlined, links, ...).
Once they get all the content entered into these various content controls I'm trying to make it easy for them to combine them together to paste in a consistent order into some podcast show notes which is in an HTML form.
So basically, I want to take three rich text content controls that have formatted data in them, combine them together into one formatted piece of content, and then copy it to the clipboard so they can then go to this web form, paste it in, and do some minor cleanup. The problem is that whenever I try to combine the RTF content it loses the formatting.
The only way I seem to be able to keep the formatting is if I copy the range object and then paste it. However, this doesn't paste just the formatted text. It pastes the whole rich text content control.
I've tried creating a blank RTF field at the bottom of the Word doc to combine everything in but I just can't figure it out. I wouldn't think this would be rocket science.
Being none of the code I've tried works and keeps the formatting I"m not sure if posting it here will do any good. Here's how I'm getting the value of the text object:
ActiveDocument.SelectContentControlsByTitle("txtShowNotes").Item(1).Range.Text
tried this:
ActiveDocument.SelectContentControlsByTitle("txtShowNotes").Item(1).Range.Copy
ActiveDocument.SelectContentControlsByTitle("txtCombinedContentSection").Item(1).Range.Paste
but this copies the whole RTF and not just the text.
Try something based on:
Sub Demo()
Dim Rng As Range
With ActiveDocument
Set Rng = .SelectContentControlsByTitle("txtCombinedContentSection").Item(1).Range
Rng.FormattedText = _
.SelectContentControlsByTitle("txtShowNotes").Item(1).Range.FormattedText
Rng.InsertAfter vbCr & vbCr
Rng.Characters.Last.FormattedText = _
.SelectContentControlsByTitle("txtShowNotes").Item(2).Range.FormattedText
End With
End Sub

VBA Macro to enter range of data from excel to website then submit form

I'm pretty new to VBA and Macros and currently trying to use VBA to gather numbers from a range of cells in a worksheet. Then put them into a form on a website and submit the form.
This is what I have so far. I'm not sure why the range won't populate the text box on the website. (http://www.centraltransportint.com/confirm/trace.aspx) If I set the range to just A2 it will put that cell's value into the textbox but won't put anymore than just the one cell.
My goal after getting the form to submit is to then copy a portion of the results from the website to be displayed in column B in Excel. I found where the information I need is stored in the next page after submitting the form so I'm feeling pretty confident I can handle that.
However, I can not seem to get a range of cells to populate the text box.
The line (IE.Document.all("_ctl0:lstType").Value = "PuN") is used to switch the drop down menu from pro number to pickup number.
Sub GetHTMLDocument()
Dim IE As New SHDocVw.InternetExplorer
IE.Visible = True
IE.navigate "http://www.centraltransportint.com/confirm/trace.aspx"
Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop
IE.Document.all("_ctl0:lstType").Value = "PuN"
IE.Document.all("_ctl0:traceNumbers").Value = ThisWorkbook.Sheets("pickups").Range("a2:a20")
IE.Document.all("_ctl0:traceSubmit").Click
End Sub
Submit button code
<input name="_ctl0:traceSubmit" id="_ctl0_traceSubmit" language="javascript" onclick='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("_ctl0:traceSubmit", "", true, "", "", false, false))' type="image" src="../images/btn_traceship.gif" border="0">
Edit: Okay it's not accepting my pickup number because it says that it doesn't include the dashes even though the macro puts the number in with the dashes(example, Cell A2 contains: PU-946-110109442013). If i manually copy and paste it into the text box it searches. But if my macro puts it in the text box it ignores the dashes.
The website pulls up "The Pickup Number must be entered in the correct format.
For example, search for PU-xxx-xxxxxxx instead of searching for PUxxxxxxxxxx. If you do not include the dashes, you will not see the status information for your shipment. "

Excel VBA - Extract/Open a dynamic hyperlink URL/Address

Greeting!
I am attempting to use excel vba to extract a dynamic hyperlink from OR use excel vba to open the dynamic hyperlink in a worksheet. I am able to click the hyperlink and it will open up correctly. So far, I am not able to find any relevant information pertaining to how to extract the URL the hyperlink is pointing to or simply open the hyperlink.
Here is the formula that is used to build the dynamic hyperlink based on a model selection.
=IFERROR(HYPERLINK(VLOOKUP(S.O.P.!$D$3,Models!$C$2:$G$296,4,FALSE), "Click Here to Open Box Label"), "Unable to retrieve part information")
So based on a selection the user makes this formula goes and finds the respective link that will be used to create the hyperlink.
What I want: Using a button - open the file(PDF) to allow the users to easily print the files they need from one button. I am trying to minimize human touches to eliminate the possibility for human errors.
I have also attempted to record a macro to open up the link, but it only takes me to the worksheet that the hyperlink is placed in.
Here are links to other post that were not able to resolve my issue, but provided good information...
Excel VBA Get hyperlink address of specific cell
Extract URL From Excel Hyperlink Formula
Thank you, I look forward to some helpful responses c:
let me know if I need to elaborate or clarify anything!
Any reason you cant run the vlookup in VBA. Then you will have the link address as a string which you can then do what you want with:
Sub GetLink()
Dim ReturnedAddress As String
ReturnedAddress = Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets("S.O.P.").Range("D3"), ThisWorkbook.Sheets("Models").Range("C2:G296"), 4, 0)
end sub

VBA to open Excel hyperlink does not work when hyperlink generated with a formula

There seems to be a bug with Excel hyperlinks which are generated with a formula. I'm using Excel 2010. I have a spreadsheet with cells containing URLs, and my goal is to do the following two things:
Turn these cells into hyperlinks.
Create a keyboard shortcut to open these hyperlinks so I don't have to use the mouse.
To do #1, initially I just used the function =HYPERLINK(). So, my URLs are in column A, and I used this formula to make hyperlinks in column B.
To do #2, I created the following macro which should open the hyperlink with the keyboard shortcut Ctrl+H:
Sub Open_Hyperlink()
'
' Open_Hyperlink Macro
'
' Keyboard Shortcut: Ctrl+h
'
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
End Sub
The problem is that this macro only seems to work on hyperlinks which are not created using a formula. For example, if I just type into a cell http://www.google.com, Excel will automatically make this a hyperlink and the keyboard shortcut macro works, where it doesn't with formula generated hyperlinks.
I've also noticed that when I right click on formula generated hyperlinks, there is no option in the drop-down menu to open the hyperlink, yet there is that option when right clicking on hyperlinks not generated by a formula.
I've found the following workaround. Rather than generate hyperlinks using a formula, I used a macro which I found here.
Sub HyperAdd()
'Converts each text hyperlink selected into a working hyperlink
For Each xCell In Selection
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=xCell.Formula
Next xCell
End Sub
I'm able to use the keyboard shortcut to open the hyperlinks generated with this macro. I'm wondering if anyone has or had a similar problem, and why the formula generated hyperlinks are not working for me. I would prefer to use formulas to make hyperlinks in the future, since it is simpler, so if anyone knows of a way to avoid using a macro to make hyperlinks, I'd really appreciate it.
I'm wondering if anyone has had a similar problem, and why the formula
generated hyperlinks are not working for me.
Alas, this seems to be painful truth: Excel does not add to Hyperlinks collection formula-generated links - below is the screen from the debugger which is pointed to =HYPERLINK("http://www.google.com/";"Google"):
I'm not sure whether this is a deliberate implementation or a bug, but yes, formula-generated links may NOT be opened using Hyperlinks().Follow method.
However, if you're going to use keyboard shortcut for links opening, just use the following code - it will automatically convert to clickable link selected cell text and open it:
Sub Open_Hyperlink()
Selection.Hyperlinks.Add Anchor:=Selection, Address:=Selection.Formula
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
End Sub
Just assign any shortcut and you're ready to go) Here is the sample: https://www.dropbox.com/s/d4cie7lun22quma/FollowLinks.xlsm
Hope that's somehow helpful. Good luck!

How do I convert a column of text URLs into active hyperlinks in Excel?

I have a column in excel, wherein I have all the website url values. My question is I want to turn the url values to active links. There are about 200 entries in that column with different urls in all cells. Is there a way I can create active hyperlinks to all the cells without writing a macro.
If you don't want to make a macro and as long as you don't mind an additional column, then just create a new column alongside your column of URLs.
In the new column type in the formula =HYPERLINK(A1) (replacing A1 with whatever cell you are interested in). Then copy the formula down the rest of the 200 entries.
NOTE: This solution does not work if the cell A1 contains a string longer than 255 characters. It results in a #VALUE! error
Create the macro as here:
On the Tools menu in Microsoft Excel, point to Macro, and then click Visual Basic Editor.
On the Insert menu, click Module.
Copy and paste this code into the code window of the module.
It will automatically name itself HyperAdd.
Sub HyperAdd()
'Converts each text hyperlink selected into a working hyperlink
For Each xCell In Selection
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=xCell.Formula
Next xCell
End Sub
When you're finished pasting your macro, click Close and Return to Microsoft Excel on the File menu.
Then select the required cells and click macro and click run.
NOTE Do NOT select the whole column! Select ONLY the cells you wish to be changed to clickable links else you will end up in a neverending loop and have to restart Excel!
Done!
Pretty easy way for rather short lists:
Double click on the box where the url is
Enter
You have your link ;)
Here's a way I found. I'm on a Mac using Excel 2011.
If column B had the text values you want to be hyperlinks, put this formula in the cell C1 (or D1 or whatever as long as it's a free column): =HYPERLINK(B1,B1)
This will insert a hyperlink with the location as the link text and the "friendly name" as the link text. If you have another column that has a friendly name for each link, you could use that too.
Then, you could hide the text column if you didn't want to see it.
If you have a list of IDs of something, and the urls were all http://website.com/folder/ID, such as:
A1 | B1
101 | http://website.com/folder/101
102 | http://website.com/folder/102
103 | http://website.com/folder/103
104 | http://website.com/folder/104
you could use something like =HYPERLINK("http://website.com/folder/"&A1,A1) and you wouldn't need the list of urls. That was my situation and worked nicely.
According to this post: http://excelhints.com/2007/06/12/hyperlink-formula-in-excel/ this method will work in Excel 2007 as well.
OK, here's a hokey solution, but I just can't figure out how to get Excel to evaluate a column of URLs as hyperlinks in bulk.
Create a formula, ="=hyperlink(""" & A1 & """)"
Drag down
Copy new formula column
Paste Special Values-only over the original column
Highlight column, click Ctrl-H (to replace), finding and replacing = with = (somehow forces re-evaluation of cells).
Cells should now be clickable as hyperlinks. If you want the blue/underline style, then just highlight all cells and choose the Hyperlink style.
The hyperlink style alone won't convert to clickable links, and the "Insert Hyperlink" dialog can't seem to use the text as the address for a bunch of cells in bulk. Aside from that, F2 and Enter through all cells would do it, but that's tedious for a lot of cells.
If adding an extra column with the hyperlinks is not an option,
the alternative is to use an external editor to enclose your hyperlink into =hyperlink(" and "), in order to obtain =hyperlink("originalCellContent")
If you have Notepad++, this is a recipe you can use to perform this operation semi-automatically:
Copy the column of addresses to Notepad++
Keeping ALT-SHIFT pressed, extended your cursor from the top left corner to the bottom left corner, and type =hyperlink(". This adds =hyperlink(" at the beginning of each entry.
Open "Replace" menu (Ctrl-H), activate regular expressions (ALT-G), and replace $ (end of line) with "\). This adds a closed quote and a closed parenthesis (which needs to be escaped with \ when regular expressions are activated) at the end of each line.
Paste back the data in Excel. In practice, just copy the data and select the first cell of the column where you want the data to end up.
I shocked Excel didn't do this automatically so here is my solution I hope would be useful for others,
Copy the whole column to clipboard
Open this on your Chrome or Firefox
data:text/html,<button onclick="document.write(document.body.querySelector('textarea').value.split('\n').map(x => '<a href=\'' + x + '\'>' + x + '</a>').join('<br>'))">Linkify</button><br><textarea></textarea>
Paste the column on the page you just opened on the browser and press "Linkify"
Copy the result from the tab to the the column on Excel
Instead step two, you can use the below page, first, click on "Run code snippet" then paste the column on it
<button onclick="document.write(document.body.querySelector('textarea').value.split('\n').map(x => '<a href=\'' + x + '\'>' + x + '</a>').join('<br>'))">Linkify</button><br><textarea></textarea>
This method works for me using the hyperlink function:
=HYPERLINK("http://"&B10,B10)
Where B10 is the cell containing the text version of the URL (in this example).
With Excel 2007 on Windows, I found these steps simplest;
Select cells with the non-active URLs
Copy
Paste as hyperlink
Create a temporary new column of hyperlinks using formula =HYPERLINK()
Copy that column into Microsoft Word (copy to clipboard only after Word is running).
Copy everything in the new word document (ctrl+a, then ctrl+c).
Paste into Excel, replacing the original column of text. Delete the temporary column with the formula.
I found that none of the methods here worked if the hyperlink did not include http:// as they linked to local locations.
I also wanted to fool-proof the script as the users would not be able to maintain it themselves and I would not be available.
It will only run on cells in a selected range if they contain a dot and no spaces. It will only run for up to 10,000 cells.
Sub HyperAdd()
Dim CellsWithSpaces As String
'Converts each text hyperlink selected into a working hyperlink
Application.ScreenUpdating = False
Dim NotPresent As Integer
NotPresent = 0
For Each xCell In Selection
xCell.Formula = Trim(xCell.Formula)
If xCell.Formula = "" Or InStr(xCell.Formula, ".") = NotPresent Then
'Do nothing if the cell is blank or contains no dots
Else
If InStr(xCell.Formula, " ") <> 0 Then
CellsWithSpaces = CellsWithSpaces & ", " & Replace(xCell.Address, "$", "")
GoTo Nextxcell
End If
If InStr(xCell.Formula, "http") <> 0 Then
Hyperstring = Trim(xCell.Formula)
Else
Hyperstring = "http://" & Trim(xCell.Formula)
End If
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=Hyperstring
End If
i = i + 1
If i = 10000 Then Exit Sub
Nextxcell:
Next xCell
If Not CellsWithSpaces = "" Then
MsgBox ("Please remove spaces from the following cells:" & CellsWithSpaces)
End If
Application.ScreenUpdating = True
End Sub
For me I just copied the entire column which has the URLs in text format into another application (say Evernote), and when they were pasted there they became links, and then I just copied them back into Excel.
The only thing here is you need to make sure the data you copy back lines up with the rest of the columns.
Try this:
=HYPERLINK("mailto:"&A1, A1)
Replace A1 with your text of email address cell.
For anyone landing here with Excel 2016, you can simply highlight the column, then click the Hyperlink tab located on the Home ribbon in the Styles box.
Edit: Unfortunately, this only updates the cell style, not the function.
You can insert the formula =HYPERLINK(<your_cell>,<your_cell>) to the adjacent cell and drag it along all the way to the bottom. This will give you a column with all the links. Now, you can select your original column by clicking on the header, right-click, and select Hide.
If you copy the text contents into a new column and use:
=HYPERLINK("http://"&B10,B10)
on your original column. Then use the $ for the column so it looks like this:
=HYPERLINK("http://"&$B10,$B10)
That's the only way it worked for me on Excel 2010 on Windows 7. You can copy down the formula.
Put the URLs into an HTML table, load the HTML page into a browser, copy the contents of that page, paste into Excel. At this point the URLs are preserved as active links.
Solution was proposed on http://answers.microsoft.com/en-us/mac/forum/macoffice2008-macexcel/how-to-copy-and-paste-to-mac-excel-2008-a-list-of/c5fa2890-acf5-461d-adb5-32480855e11e by (Jim Gordon Mac MVP)[http://answers.microsoft.com/en-us/profile/75a2b744-a259-49bb-8eb1-7db61dae9e78]
I found that it worked.
I had these URLs:
https://twitter.com/keeseter/status/578350771235872768/photo/1
https://instagram.com/p/ys5ASPCDEV/
https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg
https://twitter.com/ranadotson/status/539485028712189952/photo/1
https://instagram.com/p/0OgdvyxMhW/
https://instagram.com/p/1nynTiiLSb/
I put them into an HTML file (links.html) like this:
<table>
<tr><td>https://twitter.com/keeseter/status/578350771235872768/photo/1</td></tr>
<tr><td>https://instagram.com/p/ys5ASPCDEV/</td></tr>
<tr><td>https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-15/10881854_329617847240910_1814142151_n.jpg</td></tr>
<tr><td>https://twitter.com/ranadotson/status/539485028712189952/photo/1</td></tr>
<tr><td>https://instagram.com/p/0OgdvyxMhW/</td></tr>
</table>
Then I loaded the links.html into my browser, copied, pasted into Excel, and the links were active.
Thank you Cassiopeia for code. I change his code to work with local addresses and made little changes to his conditions. I removed following conditions:
Change http:/ to file:///
Removed all type of white space conditions
Changed 10k cell range condition to 100k
Sub HyperAddForLocalLinks()
Dim CellsWithSpaces As String
'Converts each text hyperlink selected into a working hyperlink
Application.ScreenUpdating = False
Dim NotPresent As Integer
NotPresent = 0
For Each xCell In Selection
xCell.Formula = Trim(xCell.Formula)
If InStr(xCell.Formula, "file:///") <> 0 Then
Hyperstring = Trim(xCell.Formula)
Else
Hyperstring = "file:///" & Trim(xCell.Formula)
End If
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=Hyperstring
i = i + 1
If i = 100000 Then Exit Sub
Nextxcell:
Next xCell
Application.ScreenUpdating = True
End Sub
I had a list of numbers that feed into url's I want hotlinked.
For example I have Column A with question numbers (i.e., 2595692, 135171) and I want to turn these question numbers into hotlinks and to display only the question numbers.
So I built a text-only hyperlink pointing to Column A, and copied it down for all my question numbers:
="=HYPERLINK("&"""http""&"":"""&""&"&"&"""//stackoverflow.com/questions/"&A1&""""&","&A1&")"
Then I copy - paste value this column of text hyperlinks to another column.
You end up with a column of text that looks like the following:
=HYPERLINK("http"&":"&"//stackoverflow.com/questions/2595692",2595692)
Then I selected these pasted items and ran the F2Entry Macro that follows:
Sub F2Enter()
Dim cell As Range
Application.Calculation = xlCalculationManual
For Each cell In Selection
cell.Activate
cell = Trim(cell)
Next cell
Application.Calculation = xlCalculationAutomatic
EndSub
I then deleted the text entry column and Column A.
I ended up with a single column of hotlinked question numbers:
2595692
135171
etc.
Cheers
On Mac, a dead easy way to do it is select your entire spreadsheet in Excel, copy, launch Numbers, paste, then select all, copy, and paste back into Excel.
Easiest way here
Highlight the whole column
click ''insert''
click ''Hyperlink''
click ''place in this document''
click ok
thats all
The simplest way in Excel 2010:
Select the column with the URL text, then select Hyperlink Style from the Home tab.
All URLs in the column are now hyperlinks.
Also double clicking each cell at the end of the URL text and adding a blank or just enter will also produce a hyperlink. Similar to the way you have to create URL links in MS Outlook emails.
There is a very simple way to do this. Create one hyperlink, and then use the Format Painter to copy down the formatting. It will create a hyperlink for every item.