VBA delete Formula Sign from Excel - excel

I am doing a validation at work and already did a lot of work, but now I am facing a problem. I need to delete the ' sign to clear unwanted Excel Formulas. I tried with Replace but it did not remove the '. Does anyone know how to delete it from a cell?

The apostrophe is kept hidden, not as part of the value so you cannot check for it via value or text or formula property. What you need to check for is the PrefixCharacter. Alas, that is read-only.
Only way around this: clear the cell and re-set it.
Short example that you should be able to implement:
Dim txt As String, r As Range
Set r = Cells(2, 1) 'contains apostrophe
If r.PrefixCharacter = "'" Then
txt = r.Value
r.Clear
r.Value = txt
End If
Put this in an appropriate loop for your cell contents and you should be set.

Related

Excel Changes number value automatically

I´m trying to remove the dollar sign in a column which should only include numbers. Therefore I tried to to use simply change the cell format to number but nothing changed.
Now I copied the values inside a text editor and removed the dollar signs. After inserting excel automaticallly changes some values to different numbers.
For Exaxmple it changed 8.59 to 21763,00. When I change the cell format to standard then it displays me something like 28 Jan except 8.59.
In this picture I tried to illustrate my problem with the different columns. Sold Price in Thousands is the original column which I liked to change.
Select the cells you wish to fix and run this short macro:
Sub FixData()
Dim r As Range, s As String
For Each r In Intersect(Selection, ActiveSheet.UsedRange)
s = r.Text
If Left(s, 1) = "$" Then
r.Clear
r.Value = Mid(s, 2)
r.NumberFormat = "0.00"
End If
Next r
End Sub
this is a known issue and the only work around that you can use is the following:
Copy the correct values in notepad.
From notepad make a Find and Replace in order to remove the $ sign.
Select a blank column in excel and set its format to TEXT.
Only now you can copy back the values from notepad to the new TEXT column.
This should fix your issue.

Search and Replace random cell text by first :

I have a slew of rows (100K+) to search and modify the contents.
For example the cells contain similiar text as DGC9610411:DB:10:82
All of this text can change per row except that fact that the : means something to me.
In this and every other row, i need to remove the first : and all the text after so that the cell would look like this DGC9610411
Next I will be adding the contents of another cell to the end. I think that will be an easy step and I could most likely figure that out without much effort.
I have this code in a while loop for each row. so the code is looking at one row at a time.
I have searched but everyone seems to have a different set of needs.
Just use Find and Replace, no need for vba or formulas.
Select the column containing the data that you need to modify
Press Ctrlh to open the Find and Replace dialog.
In the "Find what:" field, type :*
In the "Replace with:" field, leave it blank
Click Replace All
EDIT: If it has to be VBA, this simple macro will accomplish the same thing. Be sure to change the A to your actual column letter.
Sub tgr()
Columns("A").Replace ":*", ""
End Sub
EDIT: Upon request I am adding a formula solution. In cell B1 and copied down:
=LEFT(A1,FIND(":",A1&":")-1)
Try this small macro:
Sub colonoscopy()
Dim c As String
Dim r As Range, I As Long
For Each r In ActiveSheet.UsedRange
v = r.Value
I = InStr(1, v, ":")
If I > 0 Then
r.Value = Mid(v, 1, I - 1)
End If
Next r
End Sub

VBA convert all cells in column to type text

I'm using VBA to do some further formatting to a generated CSV file that's always in the same format. I have a problem with my For Each Loop. the loop deletes an entire row if there is more than one blank row which can be determined from the first column alone.
Dim rowCount As Integer
For Each cell In Columns("A").Cells
rowCount = rowCount + 1
'
' Delete blank row
'
If cell = "" And cell.Offset(1, 0) = "" Then
Rows(rowCount + 1).EntireRow.Delete
spaceCount = 0
End If
Next
At some point the value in the loop one of the calls does not have a value of "", it's just empty and causes it to crash. To solve this I think that changing the type of the cell to text before that compare would work but I can't figure out how (no intellisense!!!)
So how do you convert a cell type in VBA or how else would I solve the problem?
Thanks.
Use cell.Value instead of the cell.Text as it will evaluate the value of the cell regardless of the formating. Press F1 over .Value and .Text to read more about both.
Be carefull with the statement For Each cell In Columns("A").Cells as you will test every row in the sheet (over a million in Excel 2010) and it could make Excel to crash.
Edit:
Consider also the funcion TRIM. It removes every empty space before and after a string. If in the cell there is a white space " "; it will look like empty for the human eye, but it has a space inside therefore is different than "". If you want to treat it like an empty cell, then try:
If Trim(cell.value) = "" then
As #andy (https://stackoverflow.com/users/1248931/andy-holaday) said in a comment, For Each is definitely the way to go. This even allows for there to be spaces in between lines.
Example code:
Sub ListFirstCol()
Worksheets("Sheet1").Activate
Range("A1").Activate
For Each cell In Application.Intersect(Range("A:A"), Worksheets("Sheet1").UsedRange)
MsgBox (cell)
Next
End Sub
Thanks Andy!

Exceeding Max Char Limit in Excel

How do I use more than 255 characters in Excel's CONCATENATE function? I am actually also using the CONCATENATE function within the HYPERLINK function in EXCEL. An example looks like this:
=HYPERLINK(CONCATENATE("http://www.google/com/morethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255chars","morethan255chars morethan255charsmorethan255charsmorethan255charsmorethan25"),"link");
UPDATE: It's not issue with CONCATENATE function, but an issue with the first parameter of the HYPERLINK function. Using a string longer than 255 characters directly/indirectly (ex: =HYPERLINK(K204,"link") where K204 contains the 256-character length link) fails the HYPERLINK function
I realize that I can use a URL shortener, but I am doing this for ALOT of links which would require ALOT of manual use of the URL shortener.
UPDATE: Because of Karls comment I revisited my answer an found out, that Excel 2007 does not seem to allow User Defined Functions to set hyperlinks anymore (quite sensibly, see my own comment in the code). So the original code (below the line) does not work in more recent versions of Excel (I haven't tested Excel 2010 but I assume the result is the same). For historical reasons I do not delete the old code (an editor might think otherwise -- feel free to edit/ delete accordingly).
So what remains is to set long hyperlinks programatically, e.g.
Sub insertVeryLongHyperlink()
Dim curCell As Range
Dim longHyperlink As String
Set curCell = Range("A1") ' or use any cell-reference
longHyperlink = "http://www.veryLongURL.com/abcde" ' Or a Cell reference like [C1]
curCell.Hyperlinks.Add Anchor:=curCell, _
Address:=longHyperlink, _
SubAddress:="", _
ScreenTip:=" - Click here to follow the hyperlink", _
TextToDisplay:="Long Hyperlink"
End Sub
What follows does not work in Excel 2010 anymore; see my comment above
The "copy the hyperlink from Word and paste into Excel" got me thinking. So obviously the limit is both in the built-in HYPERLINK-function and in the dialog-window 'edit hyperlink'. On the other hand it should be -- and actually is -- possible to set longer hyperlinks via VBA.
This code does not work in Excel 2010 anymore
Function myHyperlink(cell As Range, _
hyperlinkAddress As String, _
Optional TextToDisplay As Variant, _
Optional ScreenTip As Variant)
' Inserts a Hyperlink
' at the position cell (this should be the position where the UDF is used,
' since the return value of the UDF is = TextToDisplay)
' with the hyperlinkAddress
' optional TextToDisplay
' optional ScreenTip
' #######################################
' Warning Warning Warning Warning Warning
' #######################################
' 1) Since it is really bad practice to have a function perform procedural
' tasks, you should not do this.
' 2) You have no garantee, the link is updated when the value hyperlinkAddress changes
' USE AT YOUR ONE RISK AND ONLY IN CASE OF EMERGENCIES :-)
' If more than one cell is selected as target range,
' use the top left cell
Set cell = cell.Resize(1, 1)
If IsMissing(TextToDisplay) Then
TextToDisplay = hyperlinkAddress
End If
If IsMissing(ScreenTip) Then
ScreenTip = hyperlinkAddress & " - Click here to follow the hyperlink"
End If
cell.Hyperlinks.Add Anchor:=ActiveCell, _
Address:=hyperlinkAddress, _
SubAddress:="", _
ScreenTip:=ScreenTip, _
TextToDisplay:=TextToDisplay
' There doesn't seem to be another way to set TextToDisplay
myHyperlink = TextToDisplay
End Function
Use as a normal Excel-function, but be sure to add the current cell as first parameter (i.e. the following formula is inserted in cell A1)
=myHyperlink(A1,B1)
=myHyperlink(A1,B1,"TextToDisplay", "ScreenTip")
You can neither pull the formula down nor copy it to another cell. If you do that you have to let the formula be recalculated (neither ALT-CTRL-F9 nor ALT-CTRL-SHIFT-F9 as force recalculate seem to work) so go into each cell, press F2 to activate it and finish with Return.
I hope I am not helping you to screw up too many Excel-Workbooks.
It is probably safer to write an VBA that is explicitly started that iterates through a list and writes to hyperlinks. That way they can reused and there are no functions.
Regards
Andreas
I have Excel 2007 and I tried making a cell with 300 characters in A1, and another with 300 different characters in B1.
Then I made C1 = CONCATENATE(A1, B1).
I can see all of the characters from both cells. Nothing is missing or truncated and no errors were received. It looks good to me.
What makes you think that the concatenate is failing? Are you having trouble seeing your results? If your cell contains more than 1,024 characters only the first 1,024 are displayed in the cell. However they are still there and if you copy and paste them all of the characters will be copied.
Edit:
Now that you have editted your question I realize the problem is with HYPERLINK and not CONCATENATE.
The only way to get around the 255 character limit of HYPERLINK formula in Excel is to copy a hyperlink from Word and paste it into a cell in Excel. Then it can be super long. I know this is an unreasonable manual process if you have a lot of links but it seems the only way to get it into an Excel spreadsheet and yet still have it be a hyperlink that you can click on and be redirected. If you don't need it to act like a hyperlink then I would suggest rewriting your queries to return the hyperlink as its own text field and then it will be fine.
You might be out of luck. It seems that the character limit for hyperlinks in Excel is 256 as pointed out here. If you test it out yourself (I have Excel 2007, too), =HYPERLINK(REPT("a",255)) works and =HYPERLINK(REPT("a",256)) does not and throws a #VALUE! error.
Here's some VBA which uses bitly.com to shorten a URL. It is based on the bitly API documentation.
Create a free account on bitly.
Valid email address with bitly.
Get access token from bitly.
Substitute the access token in the VBA code below where it says MY_TOKEN.
Copy and paste the code in Excel's VBA.
In a cell, write the following '=Hyperlink(GetURL("some really long URL"))' without single quote ' marks. Note: Instead of passing a string to GetURL(), pass a reference to a cell which has a URL in it as text.
Public Function GetURL(longUrl As String) As String
Dim xml As Object
longUrl = URLEncode(longUrl)
Set xml = CreateObject("MSXML2.XMLHTTP.6.0")
xml.Open "GET", "https://api-ssl.bitly.com/v3/shorten?format=xml&access_token=MY_TOKEN=" & longUrl, False
xml.Send
GetURL = xml.responsetext
head = InStr(GetURL, "<url>") + 5
tail = InStr(GetURL, "</url>")
GetURL = Mid(GetURL, head, tail - head)
End Function
Function URLEncode(ByVal Text As String) As String
Dim i As Integer
Dim acode As Integer
Dim char As String
URLEncode = Text
For i = Len(URLEncode) To 1 Step -1
acode = Asc(Mid$(URLEncode, i, 1))
Select Case acode
Case 48 To 57, 65 To 90, 97 To 122
' don't touch alphanumeric chars
Case 32
' replace space with "+"
Mid$(URLEncode, i, 1) = "+"
Case Else
' replace punctuation chars with "%hex"
URLEncode = Left$(URLEncode, i - 1) & "%" & Hex$(acode) & Mid$(URLEncode, i + 1)
End Select
Next
End Function
Dunno if my answer is still useful but I had the same issue couple of days ago, the best way and proved way to do a workable hyperlink that exceeds a 255 char limit is to first split it, with CONCATENATE(), and use the cell with CONCATENATE() function in VBA.
For me it looks like:
A1 = LinkPart1
A2 = LinkPart2
A3 = LinkPart3
A5 = CONCATENATE( A1; A2; A3 )
VBA Code you need to link with A5:
Sub insertVeryLongHyperlink()
Dim curCell As Range
Dim longHyperlink As String
Set curCell = Range("A7") ' or use any cell-reference
longHyperlink = [A5]
curCell.Hyperlinks.Add Anchor:=curCell, _
Address:=longHyperlink, _
SubAddress:="", _
ScreenTip:=" - Click here to follow the hyperlink", _
TextToDisplay:="Click Here"
End Sub
Quick update for those who run into this problem - and for the support staff who suggest that the issue is perhaps too old to talk about:
Excel for Microsoft 365 MSO (Version 2203 Build 16.0.15028.20102) still has this bug.
It's a bit inexcusable, when typical URLs that you want to parameterize (a common usage in Excel) easily exceed 255, and most internet software has a default limit of 1024 characters... many even allow exceeding that by configuration.
This is a 12-year-old problem that has never been fixed.
Instead of writing
=CONCATENATE("Toto";"Tata")
Put Toto in cell Z1 (for exemple) and Tata in cell Z2 and write
=CONCATENATE(Z1;Z2)
Guys I think a URL Shortening VBA will help you. Here is one which I found today. It works like a charm:
http://www.jpsoftwaretech.com/shorten-urls-with-bit-ly-web-api-and-vba/
The Hyperlink function has a hard limit that can't be overstaped. I had a similar problem and I simply imported the Excel sheet into Open Office Calc and voila - everything worked instantly and the hyperlink that was to long previously can be now as long as I wanted it to be.
You can use the VBA Shell() routine to execute a browser and pass the URL to it on the command line passed via the Shell() call. Thus the URL can be any length supported by the shell mechanism.
Furthermore you can get this URL from any cell value by having the user double-click that cell. This value can be constructed from many cells via a single CONCATENATE() function call! That's right: just a single call. The CONCATENATE() will take a large number of parameters and will create a string well-bigger than 255 characters. You don't need to laboriously join many separate concatenations or use loads of "builder" cells. One will do!
The macro needs to be created by opening the VIEW CODE option when you right-click the tab at the bottom of the worksheet. Then write the following phenomenally short, simple and painless bit of code:
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Selection.Count = 1 Then
If Left(Target.Value, 7) = "HTTP://" Then
Cancel = True
Shell ("""" + Range("Browser").Value + """" + " " + """" + Target.Value + """")
End If
End If
End Sub
Note that "Browser" is a named cell that should contain the unquoted path of your browser, be that IE, Opera, Mozilla or Chrome. You have to name the cell yourself, or change the macro to have a hard cell reference like "A2". And of course, that cell value must be a valid browser path!
Once you have all of this in place, you can double-click ANY cell that has a value starting with the text "HTTP://" and Excel will open the browser with that full value, no-matter how long it is. All you then need is to build your string in that cell and perhaps format it colour/font-wise to make it obvious that it is a hyperlink cell to be double-clicked. A textual hint nearby may also be in order!
Incidentally, an alternative to the Shell() line in the macro is:
ThisWorkbook.FollowHyperlink Address:=Target.Value
Whilst this will also process URLs bigger than 255 characters, I found that this FollowHyperlink() function causes the URL to be sent TWICE. Once by the Excel function itself (presumably to test it) and then again by the default browser that Excel opens! This may not be desirable (and wasn't in my case). This is why I ended up using the Shell() function instead.
You can create a hyperlink in Microsoft Word, and then copy it over to Excel.
For some reason, those hyperlink elements are not limited by the 255 character limit, but you won't be able to use the HYPERLINK() function.
Source
Assuming you do not have very many hyperlink URLs >255 characters, just use the Link function. The link function is available from the right-click menu. No need to go to Word or any other MSOffice application.
I know this works as I have a URL that is 281 characters long and that one works.
I only have two very long URLs in my sheet so when/if they need updating I am making a note that they must be done in the target cell vs. on my sheet of hyperlink addresses.
Working off of Andreas J's answer, you can use the below VBA code snippet to generate a column of hyperlinks from a column of plain-text URIs. Assuming column A contains the plain-text URIs and column B contains the desired link text, the following code loops through each row in Range("A:C") and generates a hyperlink in column C:
Sub createLink(a As Range, b As Range, c As Range)
Dim curCell As Range
Dim longHyperlink As String
Dim linkText As String
Set curCell = a
longHyperlink = b
linkText = c
curCell.Hyperlinks.Add Anchor:=curCell, _
Address:=longHyperlink, _
SubAddress:="", _
ScreenTip:="", _
TextToDisplay:=linkText
End Sub
Sub insertLinks()
Dim a As Range, b As Range
Set a = Range("A:C")
For Each b In a.Rows
Dim curCell As Range, longHyperlink As Range, linkText As Range
Set curCell = b.Cells().Item(1, 3)
Set longHyperlink = b.Cells().Item(1, 1)
Set linkText = b.Cells().Item(1, 2)
If longHyperlink = "" Then
Exit For
End If
createLink curCell, longHyperlink, linkText
Next
End Sub

How to Insert Double or Single Quotes

I have a long list of names that I need to have quotes around (it can be double or single quotes) and I have about 8,000 of them. I have them in Excel without any quotes and I can copy all of the names and paste them no problem but there are still no quotes. I have looked and looked for an Excel formula to add quotes to the name in each row but I have had no luck. I have also tried some clever find and replace techniques but no have worked either. The format I am looking for is this:
"Allen" or 'Allen'
Any of those would work. I need this so I can store the info into a database. Any help is greatly appreciated. Thanks
PS:
I have found other people online needing the same thing done that I need done and this solution has worked for them but I do not know what do with it:
You can fix it by using a range
variable (myCell for example) and then
use that to iterate the 'selection'
collection of range objects, like so
Sub AddQuote()
Dim myCell As Range
For Each myCell In Selection
If myCell.Value <> "" Then
myCell.Value = Chr(34) & myCell.Value
End If
Next myCell
End Sub
Another solution that also worked for others was:
Sub OneUglyExport()
Dim FileToSave, c As Range, OneBigOleString As String
FileToSave = Application.GetSaveAsFilename
Open FileToSave For Output As #1
For Each c In Selection
If Len(c.Text) <> 0 Then _
OneBigOleString = OneBigOleString & ", " & Chr(34) & Trim(c.Text) & Chr(34)
Next
Print #1, Mid(OneBigOleString, 3, Len(OneBigOleString))
Close #1
End Sub
To Create New Quoted Values from Unquoted Values
Column A contains the names.
Put the following formula into Column B
= """" & A1 & """"
Copy Column B and Paste Special -> Values
Using a Custom Function
Public Function Enquote(cell As Range, Optional quoteCharacter As String = """") As Variant
Enquote = quoteCharacter & cell.value & quoteCharacter
End Function
=OfficePersonal.xls!Enquote(A1)
=OfficePersonal.xls!Enquote(A1, "'")
To get permanent quoted strings, you will have to copy formula values and paste-special-values.
Assuming your data is in column A, add a formula to column B
="'" & A1 & "'"
and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.
Easier steps:
Highlight the cells you want to add the quotes.
Go to Format–>Cells–>Custom
Copy/Paste the following into the Type field: \"#\" or \'#\'
Done!
Why not just use a custom format for the cell you need to quote?
If you set a custom format to the cell column, all values will take on that format.
For numbers....like a zip code....it would be this '#'
For string text, it would be this '#'
You save the file as csv format, and it will have all the quotes wrapped around the cell data as needed.
Or Select range and Format cells > Custom \"#\"
If you save the Excel file as a CSV format file, you might find that the result is convenient to inserting into a database, though I'm not sure all of the fields would be quoted.
I would like to thank Guria for the answer
from https://www.exceldemy.com/
I would like to summarize the methods, there are more than 4 methods:
Let A1 be your cell where you want to insert quotes.
1 .
For Double Quotes:
=CHAR(34)&A1&CHAR(34)
For Single Quotes:
=CHAR(39)&A1&CHAR(39)
2 .
=CONCATENATE("'",A1,"'")
3 .
="'"&A1&"'"
4 . Apply Custom Format.
Suppose you have a number and you have to insert quotes on that number:
Right click the cells:
Then click Format Cells
You will get this screen:
In the Type box write
'#'
Click 'OK' at the bottom of the screen.
You will get the result:
If you have text written in the cell then:
Click 'OK' at the bottom of the screen.

Resources