Inputbox is not accepting double number VBA excel - vba

I have a declaration like number= InputBox("Number for:", "Number:"), number is declared as Dim number As Double but when I enter a double number, for example 5.4, into the Inputbox and transmit it into a cell, the cell shows me 54, it deletes the point.
How can I fix this?
THX

If you want to detect which settings your Excel uses for the Decimal seperator, try the code below:
MsgBox "Excel uses " & Chr(34) & Application.DecimalSeparator & Chr(34) & " as a decimal seperator"
if you want to change it to ., then use the line below:
Application.DecimalSeparator = "."

Unfortunately, VBA is horrible at handling differences in decimal seprators. In your case, you should probably use a comma (,), instead of a punctuation/dot (.).
Edit: Using the Application.DecimalSeparator method, it now works regardless of regional settings. Be aware though, it seems to cause some issues if you change the comma separator settings for Excel (it seems that VBA somewhat ignores this setting). If you do not change that however, the example should work in all other cas
Sub GetNumberFromInputBox()
Dim val As String
Dim num As Double
'Get input
val = InputBox("Number for:", "Number:")
Debug.Print Application.DecimalSeparator
If IsNumeric(val) Then
'Try to convert to double as usual
num = CDbl(val)
'If the dot is removed automatically, then
'you will se a difference in the length. In
'those cases, replace the dot with a comma,
'before converting to double
If Len(val) <> Len(num) Then
If Application.DecimalSeparator = "," Then
num = CDbl(Replace(val, ".", ","))
Else
num = CDbl(Replace(val, ",", "."))
End If
End If
'Pring the number
Debug.Print "You selected number: " & num
Else
'If its not a number at all, throw an error
Debug.Print "You typed " & val & ", which is not a number"
End If
End Sub

Related

Taking a String and Removing text inbetween brackets

I'm trying to make a simple text converter program for my first Visual Basic program. I've already written this in Python but I'm not sure how to do it in Visual Basic.
I need the program to run through the characters of a string and once it encounters a ( to then remove the bracket and ignore the rest of the text until it encounters a ).
For Example,
"This is a (not so good) sentence",
becomes
"This is a Sentence".
Previously I did this with a for loop what looked at a character in the string, then checked if it was open. If it wasn't it would append the character to an output string to the next character or if it was it would then trigger a Boolean to true what would stop the character being appended. It would then continue to stop the future characters from being appended until it found a close bracket. At that point, it would then make the Boolean false, stop the closed bracket from being appended and move back to appending characters, unless it was another bracket.
Sorry if this description is a bit rough as I'm not the best at describing things and I'm very new to visual basic. Thanks for any help given
You can achieve this by several different methods. Here is one method using Instr. Instr returns the character position (index) of a given string in another string. You can use this to determine the bounds of where to include/exclude the string chunk.
You didn't specify if there could be multiple sections encapsulated in () so I assumed there wouldn't be. However, this is a relatively easy tweak by adding either a Do...Loop or a While... loop in the Function.
Hope it helps:
Option Explicit
Public Function removeBrackets(Source As String, Optional RemoveDoubleSpaces As Boolean = False)
Dim FirstBracket As Long
Dim SecondBracket As Long
FirstBracket = InStr(1, Source, "(")
SecondBracket = InStr(1, Source, ")")
If FirstBracket >= SecondBracket Or FirstBracket = 0 Or SecondBracket = 0 Then Exit Function
removeBrackets = Left$(Source, FirstBracket - 1) & Right$(Source, Len(Source) - SecondBracket)
If RemoveDoubleSpaces Then removeBrackets = Replace$(removeBrackets, " ", " ")
End Function
'Run this
Sub Test()
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good) sentence") ' Example given
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good) sentence", True) ' Example given, slight revision. Remove double spaces
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good sentence") ' missing ending bracket
Debug.Print "The value returned is: " & removeBrackets("This is a not so good) sentence") ' missing starting bracket
Debug.Print "The value returned is: " & removeBrackets("This is a not so good sentence") ' No brackets
End Sub

MS Access VBA: Split string into pre-defined width

I have MS Access form where the user pastes a string into a field {Vars}, and I want to reformat that string into a new field so that (a) it retains whole words, and (b) "fits" within 70 columns.
Specifically, the user will be cutting/pasting variable names from SPSS. So the string will go into the field as whole names---no spaces allowed---with line breaks between each variable. So the first bit of VBA code looks like this:
Vars = Replace(Vars, vbCrLf, " ")
which removes the line breaks. But from there, I'm stumped---ultimately I want the long string that is pasted in the Vars field to be put on consecutive multiple lines that each are no longer than 70 columns.
Any help is appreciated!
Okay, for posterity, here is a solution:
The field name on the form that captures the user input is VarList. The call to the SPSS_Syntax function below returns the list of variable names (in "Vars") that can then be used elsewhere:
Vars = SPSS_Syntax(me.VarList)
Recall that user input into Varlist comes in as each variable (word) with a line break in between each. The problem is that we want the list to be on one line (horizontal, not vertical) AND a line can be no more than 256 characters in length (I'm setting it to 70 characters below). Here's the function:
Public Function SPSS_Syntax(InputString As String)
InputString = Replace(InputString, vbNewLine, " ") 'Puts the string into one line, separated by a space.
MyLength = Len(InputString) 'Computes length of the string
If MyLength < 70 Then 'if the string is already short enough, just returns it as is.
SPSS_Syntax = InputString
Exit Function
End If
MyArray = Split(InputString, " ") 'Creates the array
Dim i As Long
For i = LBound(MyArray) To UBound(MyArray) 'for each element in the array
MyString = MyString & " " & MyArray(i) 'combines the string with a blank space in between
If Len(MyString) > 70 Then 'when the string gets to be more than 70 characters
Syntax = Syntax & " " & vbNewLine & MyString 'saves the string as a new line
MyString = "" 'erases string value for next iteration
End If
Next
SPSS_Syntax = Syntax
End Function
There's probably a better way to do it but this works. Cheers.

Removing All Spaces in String

I created a macro for removing all whitespace in a string, specifically an email address. However it only removes about 95% of the whitespace, and leaves a few.
My code:
Sub NoSpaces()
Dim w As Range
For Each w In Selection.Cells
w = Replace(w, " ", "")
Next
End Sub
Things I have tried to solve the issue include:
~ Confirmed the spaces are indeed spaces with the Code function, it is character 32 (space)
~ Used a substitute macro in conjuction with the replace macro
~ Have additional macro utilizing Trim function to remove leading and trailing whitespace
~ Made a separate macro to test for non-breaking spaces (character 160)
~ Used the Find and Replace feature to search and replace spaces with nothing. Confirmed working.
I only have one cell selected when I run the macro. It selects and goes through all the cells because of the Selection.Cells part of the code.
A few examples:
1 STAR MOVING # ATT.NET
322 TRUCKING#GMAIL.COM
ALEZZZZ#AOL. COM.
These just contain regular whitespace, but are skipped over.
Just use a regular expression:
'Add a reference to Microsoft VBScript Regular Expressions 5.5
Public Function RemoveWhiteSpace(target As String) As String
With New RegExp
.Pattern = "\s"
.MultiLine = True
.Global = True
RemoveWhiteSpace = .Replace(target, vbNullString)
End With
End Function
Call it like this:
Sub NoSpaces()
Dim w As Range
For Each w In Selection.Cells
w.Value = RemoveWhiteSpace(w.Value)
Next
End Sub
Try this:
Sub NoSpaces()
Selection.Replace " ", ""
End Sub
Use "Substitute"
Example...
=SUBSTITUTE(C1:C18," ","")
Because you assume that Selection.Cells includes all cells on the sheet.
Cells.Replace " ", ""
And to add to the excellent advice from all the great contributors, try the
TRIM or LTRIM, or RTRIM and you can read more about these functions here:
https://msdn.microsoft.com/en-us/library/office/gg278916.aspx
Now this does not remove embedded spaces (spaces in between the letters) but it will remove any leading and trailing spaces.
Hope this helps.
Space Problem with Excel
ok, the only way i see this two types of space is by converting their Ascii code value of which I do it here
now to explain this function i made, it will just filter the string character by character checking if its equal to the two types of space i mentioned. if not it will concatenate that character into the string which will be the final value after the loop. hope this helps. Thanks.
Function spaceremove(strs) As String
Dim str As String
Dim nstr As String
Dim sstr As String
Dim x As Integer
str = strs
For x = 1 To VBA.Len(str)
sstr = Left(Mid(str, x), 1)
If sstr = " " Or sstr = " " Then
Else
nstr = nstr & "" & sstr
End If
Next x
spaceremove = nstr
End Function
I copied a HTML table with data and pasted in excel but the cells were filled with unwanted space and all methods posted here didn't work so I debugged and I discovered that it wasn't actually space chars (ASCII 32) it was Non-breaking space) (ASCII 160) or HTML
So to make it work with that Non-breaking space char I did this:
Sub NoSpaces()
Dim w As Range
For Each w In Selection.Cells
w.Value = Replace(w.Value, " ", vbNullString)
w.Value = Replace(w.Value, Chr(160), vbNullString)
Next
End Sub

Changing decimal separator in VBA

I've written simple code in VBA (and seen questions here and here and none of these solutions work).
Dim toString As String
toString = cell.Value & "_"
If (InStr(toString, ",")) Then
toString = Replace(toString, ",", ".")
toString = Trim(toString)
cell.Value = " " + Left(toString, (Len(toString) - 1))
End If
Unfortunately, instead of string with dot separator, excel gives me double with comma in cell.Value. What curious is, when I exchange this whitespace with "_", it converts f. ex. 12,3 into _12.3. How can I fix it?
P.S. I add "_" at the end to ensure that toString will remain String.
I've had this issue before. You need to change the formatting of the cell before you write to it.
Application.Workbooks("Book1").Sheets("Sheet1").Range("A1:A100").NumberFormat = "#"
After that line runs you can simply write to the column like this:
Cells(1,1).Value = "12.3"
Excel will keep the string formatting and not convert it to a double.
Hope this helps.

How can I convert a double to a Hex string?

I'm working on editing a project in visual basic, and don't have a whole lot of experience with vb.
I have a text box where a user can enter a number. The number should be stored as a double. Then, I need to convert the number to it's equivalent 16-byte hexadecimal representation. Any tips on how to do this?
I have just had this kind of problem. My idea was to take the time from the function Now() and to split it by the comma. Then to convert it to Hex. After some time of researching, I came up with the idea that the input should be rounded. to 8, otherwise we may get an overflow error. This is my code:
Public Function codify_time() As String
If [set_in_production] Then On Error GoTo codify_Error
Dim dbl_01 As Variant
Dim dbl_02 As Variant
Dim dbl_now As Double
dbl_now = Round(Now(), 8)
dbl_01 = Split(CStr(dbl_now), ",")(0)
dbl_02 = Split(CStr(dbl_now), ",")(1)
codify_time = Hex(dbl_01) & "_" & Hex(dbl_02)
On Error GoTo 0
Exit Function
codify_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure codify of Function TDD_Export"
End Function