Plus sign in front of Time. Assigning formula to cell in VBA - vba

I have time (hh:mm) cell in Sheet1 and I'd like to show it's value in Sheet2 prefixed with a plus sign (+00:01).
I came up with ="+"&TEXT(Sheet1!$A$1, "hh:mm"). It works fine but I don't know how to code it in VBA.
I have this so far:
result_cell.Formula = "=""+""&TEXT(" & ?????? & ", ""hh:mm"")"
I have no idea what should go in place of question marks.

Firstly, you can put the + inside the TEXT function
=TEXT(Sheet1!$A$1, "+hh:mm")
Now in VBA
result_cell.Formula = "=TEXT(Sheet1!$A$1,""+hh:mm"")"

Related

Calculating Formula After Text Paste

I have a formula that constructs a vlookup function while drawing the file path from a date input from the user, next I have a macro that takes the results of this formula and pastes them in Cell C6.
=("=" & "IF(ISNA(VLOOKUP($A6," & "'I:\CM\PC\A\TR\AT\"&TEXT(C$5,"yyyy")&"\"&TEXT(C$5,"mmmmmmmmmmm")&"\["&TEXT(C$5,"mmm")&TEXT(C$5,"d")&".xlsm]Violations Count'!$A:$B"&",2,FALSE)),"""",VLOOKUP($A6,"&"'I:\CM\PC\A\TR\AT\"&TEXT(C$5,"yyyy")&"\"&TEXT(C$5,"mmmmmmmmmmm")&"\["&TEXT(C$5,"mmm")&TEXT(C$5,"d")&".xlsm]Violations Count'!$A:$B"&",2,FALSE))")
The trouble I am having is finding a way for VBA to activate the formula instead of having it sit there in a text format as:
=IF(ISNA(VLOOKUP($A6,'I:\CM\PC\A\TR\AT\2016\December\[Dec5.xlsm]Violations Count'!$A:$B,2,FALSE)),"",VLOOKUP($A6,'I:\CM\PC\A\TR\AT\2016\December\[Dec5.xlsm]Violations Count'!$A:$B,2,FALSE))
Afterward I just have a macro autofill it down for the other names between column A6:A37.
If anyone can help me with VBA activating the cell, it would be much appreciated.
If you want to get the value of a cell (which might contain a text string) you use something like:
someVariableEtc = Range("A1").Value
If you want to set a Cell's formula using VBA, you would use something like:
Range("C6").Formula = "some text string"
Combining the two, you could come up with something like:
Range("C6").Formula = Range("A1").Value
Look this up. The evaluate function might be what you're looking for. The simplest way to use it is wrapping an expression in square brackets [].

(Excel VBA) - Draw from cell text in a macro

I'm trying to build a small macro that allows the user to format multiple different documents at once.
I would like for the user to be able to enter into a particular cell within the document containing the macro a particular piece of text.
I then want for this piece of text to be able to be drawn upon in the macro while affecting a different document.
For instance, a code to add another column might say
Worksheets(1).Range("A1").EntireColumn.Insert
Instead of specifying the column (A), I would like it to draw on a value in the host document. For instance, the user types "G" into the particular cell, and then clicks a button to run the macro, and the macro will dynamically know to affect column G in all excel documents it targets based off of the value in the host document.
I hope this makes sense.
Any suggestions for the sort of functions I should be looking at to make this work?
"Any suggestions on the sort of functions I should be looking at?"
Here's a few...
To get the value which is entered...
If the cell will always be in the same address, say A1:
' Define a string variable and set it equal to value in A1
Dim cellText as String
cellText = ThisWorkbook.ActiveSheet.Range("A1").Value
or instead of using Range you can also use Cells which takes a row and column number.
cellText = ThisWorkbook.ActiveSheet.Cells(1, 1).Value
If the cell changes then you may need to look into the Find function to look for a label/heading next to the input cell. Then you can use it (easily with Cells) to reference the input...
Once you have this variable, you can do what you like with it.
To put this value into cell B3 in another (open) workbook named "MyWorkbook", and a sheet named "MySheet" you can do:
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range("B3").Value = cellText
To insert a column at cellText, do
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range(cellText & "1").EntireColumn.Insert
Notably here, the & concatonates the strings together, so if
cellText="B"
then
cellText & "1" = "B1"
Further to your comment about moving values between sheets, see my first example here, but always refer to the same workbook. If you find yourself repeatedly typing something like
ThisWorkbook.Sheets("MySheet").<other stuff>
then you can use the With shorthand.
With ThisWorkbook.Sheets("MySheet")
' Starting anything with a dot "." now assumes the with statement first
.Range("A1").Value = .Range("A2").Value
.Range("B1").Value = .Range("B2").Value
End With
Important to note is that this code has no data validation to check the cell's value before using it! Simply trying to insert a column based on a value which could be anything is sure to make the macro crash within its first real world use!

Adding text to a cell in Excel using VBA

I've been working with SQL and Excel Macros, but I don't know how to add text to a cell.
I wish to add the text "01/01/13 00:00" to cell A1. I can't just write it in the cell because the macro clears the contents of the sheet first and adds the information afterwards.
How do I do that in VBA?
Range("$A$1").Value = "'01/01/13 00:00" will do it.
Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
You could do
[A1].Value = "'O1/01/13 00:00"
if you really mean to add it as text (note the apostrophe as the first character).
The [A1].Value is VBA shorthand for Range("A1").Value.
If you want to enter a date, you could instead do (edited order with thanks to #SiddharthRout):
[A1].NumberFormat = "mm/dd/yyyy hh:mm;#"
[A1].Value = DateValue("01/01/2013 00:00")
You need to use Range and Value functions.
Range would be the cell where you want the text you want
Value would be the text that you want in that Cell
Range("A1").Value="whatever text"
You can also use the cell property.
Cells(1, 1).Value = "Hey, what's up?"
Make sure to use a . before Cells(1,1).Value as in .Cells(1,1).Value, if you are using it within With function. If you are selecting some sheet.

Excel - Inserting formula with VBA

Hello Stackoverflow friends,
I am struggling for 1 hour with a formula I would like to insert via VBA:
Formula = "=IFERROR(VLOOKUP(Q" & j & ";Table1[#All];2;FALSE);"""")"
ThisWorkbook.Worksheets("Sheet1").Cells(j, "AE").FormulaArray = Formula
I get the following error message:
Run-time error '1004' - Application-defined or object-definied error
Is there an issue with the brackets or double quotes?
Thanks!
Replace the semicolons with commas:
Formula = "=IFERROR(VLOOKUP(Q" & j & ",Table1[#All],2,FALSE),"""")"
OpenOffice uses semicolons to separate function parameters, Excel normally uses commas, and always uses commas when setting formulas in the above fashion.
When programming in any lanugage also in VBA - better not tied up user to specific regional settings or specific excel version.
So instead of this:
Formula = "=IFERROR(VLOOKUP(Q" & j & ";Table1[#All];2;FALSE);"""")"
ThisWorkbook.Worksheets("Sheet1").Cells(j, "AE").FormulaArray = Formula
Better use this approach, when you determine exact user environment:
s = Application.International(xlListSeparator)
Formula = "=IFERROR(VLOOKUP(Q" & j & s +"Table1[#All]" + s + "2" + s + "FALSE)" + s + """"")"
ThisWorkbook.Worksheets("Sheet1").Cells(j, "AE").FormulaArray = Formula
p.s. I didn't checked the formula for the brackets etc. but just indicating the correct usage of list separator, and how to insert formulas with VBA code within cells in correct way.
As well, as previous post says - excel probably change the formula automatically when you open it. However excel do not change VBA code automatically, so be aware and pay attention to proper code in VBA.
Depending on the regional settings, the list separator (which is also used to separate parameters in functions) is either the semicolon or the comma. This applies when typing a formula into a cell.
Excel dynamically adjusts the list separator (and function names) according to the regional settings of the current computer when a file is opened.
So, if a user with German regional setting, which have the list separator ; saves a file, then a user with US regional settings and a list separator , opens the same file, Excel will adjust the German list separators in the formulas automatically.
When writing VBA, though, you will always need to use the US-English conventions for the list separator, which is the comma.

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.