Replace number format in Word - excel

I am using a excel vba code to paste some variable data to word document (using replace all function). But I cannot paste it in correct format.
I have a word document template and get some parametric value from excel and replace it with a spesific text in word document.
Set myRange = docWord.Content
myRange.Find.Execute FindText:="TEXT_TEMPLATE", ReplaceWith:=amountvariable, Replace:=wdReplaceAll, MatchCase:=True
For example; in excel file:
amountvariable = Range("A1")
My Word Document has a sentence: "The amount is TEXT_TEMPLATE."
The code takes the value A1 cell and replace the phrase "TEXT_TEMPLATE" with "amountvariable".
However the format of the number is like 10000. I want to see it as 10.000,00. How can I make it with the right number format.

Just format the string variable according your version of "right" ;-)
Option Explicit
Sub format10k()
Dim dbl10k As Double
Dim str10k As String
dbl10k = 10000#
str10k = Format(dbl10k, "#,##0.00")
Debug.Print str10k
End Sub

Related

Filepath opening multiple times in VBA

I want to bring data from another excel file, the code below works as intended, XLookup does the job BUT Windows file picker opens three times with this code. Can anyone advise why?
I've got one variable and two references to it in the formula.
Dim FileToOpen As Variant
FileToOpen = Application.GetOpenFilename()
Range("B1").Select
ActiveCell.Formula2R1C1 = _
"=XLOOKUP(RC[-1]:R[79]C[-1],'& FileToOpen &'!R11C1:R57C1,'& FileToOpen &'!R11C2:R57C2,""Not Found"",0)"
You need to distinguish between Excel and VBA. In VBA, you have a variable named FileToOpen that contains a filename. In Excel, this variable is unknown.
What you want to do is to write the content of the variable into a string. That string will then be written as a formula into a cell. Therefore you need to do some string concatenation in VBA. With you current code, VBA sees only one single string. It cannot look into that string, see that a part of a string is a variable name and replace the name with the content. Everything between the double quotes in left untouched by VBA - except if you have a pair of double quotes, this tells VBA that you want a (single) double quote character within the string.
If you want to write a formula with VBA, my advice is always to write the formula into a intermediate string variable that you can easily check with the debugger.
Change your code to
Dim formula As String
formula = "=XLOOKUP(RC[-1]:R[79]C[-1],'" & FileToOpen & "'!R11C1:R57C1,'" & FileToOpen & "'!R11C2:R57C2,""Not Found"",0)"
Debug.Print formula
ActiveCell.Formula2R1C1 = formula
See the difference? Now your formula is build from (5) pieces that VBA sees, and it will conatenate the pieces of the formula and the content of your variable.

VBA Issue with Number formatted as text when numbers include comma

I use a vba script to open another workbook. This workbook is in format .XLS and the content from a DB was stored like:
"Name1" "0" "7,98"
"Name2" "5" "1"
"Name3" "2" "7,1"
When opening the workbook with a VBA script, every cell that includes a comma, is interpreted as text and shows this warning:
The number in this cell is formatted as text or is preceded by an apostrophe
Strangely, if I open the file by double clicking, the numbers are just formatted as text and don't show any error. I guess, Excel is doing some interpretting, which doesn't work.
My code is:
Dim WorkBookImport As Workbook
Name = Application.GetOpenFilename()
If Name <> False Then
Set WorkBookImport = Workbooks.Open(Filename:=Name)
End If
I tried everything from:
Range(mycolumn).Value = Range(mycolumn).Value
For loop with CDbl(.Value)
Range(mycolumn).TextToColumns ...
Nothing works ;( Please help!
Option Explicit
Sub edksg()
Dim c As Range
Set c = Sheet1.Range("D3")
c.Value2 = CDbl(c.Value2)
End Sub
Works fine for me when cell D3 of the worksheet is formatted as text.
Of course, my location uses the comma as decimal separator, so if your location uses a different standard, the issue might be there. In that case, doing something like CDbl(Replace(c.Value2, ",", Application.DecimalSeparator, 1, -1, vbBinaryCompare)) might solve that part of the issue.
If you want to loop through the entirety of some column, the end result might look something like this, assuming the values you want to convert to numbers are in column C.
Option Explicit
Sub edksg()
Dim c As Range
Dim r As Range
Set r = Sheet1.Range("C1:C" & Sheet1.Range("C" & Sheet1.Rows.Count).End(xlUp).Row)
For Each c In r
If Len(c) > 0 Then
c.Value2 = CDbl(Replace(c.Value2, ",", Application.DecimalSeparator, 1, -1, vbBinaryCompare))
End If
Next c
End Sub
It´s a problem with the formating of the cells. You should use NumberFormat to change it.
Sub FormatNumber()
ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange") = CDbl(ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange"))
ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange").NumberFormat = "General"
End Sub
With NumberFormat you can also change it to text if you have the opposite problem, in this case you would use NumberFormat = "#"

VBA formatting number

I building a macro in excel that reads values from my workbook and fill a online form on a web-page, in one of cells I have a number, 126,25 (using comma to separate the decimal part) but when a submit this number to my online form the field display the value, 126.25
How can I format the number to use the comma format? I already try read the value as text but the result is the same
'Read value from workbook
Number = Range("C6").Value
'Trying to format
Number = Format(Number, "###,##0")
Perhaps:
Sub dural()
Number = Range("C6").Value
Number = Replace(Number, ".", ",")
MsgBox Number
End Sub
I am dealing with those issues constantly as I am in European format like you.
I stopped wondering and simply do this systematically :
dim strNumber as string
'Read value from workbook
Number = Range("C6").Value
'Trying to format
strNumber = Format(Number, "###,##0")
strNumber = replace(strNumber,".",",")
Move the number properly formatted in a string
Replace any . with , in that string
That's maybe not the most elegant solution, but that's for me at least the easiest way to remind how to trick it.

Excel VBA cell character limit

I am building a macro to export data from a custom outlook form to an excel workbook. The data will be extracted in the string format from user-defined fields in the outlook form. The string data will then be entered into the values of the excel cells. The strings may contain a huge number of characters.
I understand that each excel cell can hold 32,767 characters. What happens if I try to enter a string with more than 32,767 characters in an excel cell? What will happen to the excess characters?
I realize that the characters do not appear, but can these lost characters be recovered somehow?
They are simply lost and there is no way to recover them. You can test this out if you like:
Sub test()
Dim i As Long
Dim text As String
For i = 1 To 32767
text = text & "a"
Next
text = text & "end"
Range("A1").Value = text
'"end" will be lost
End Sub

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

Resources