VBA dots from database get loaded into textbox as comma - excel

I know the Headline sounds odd so I will start off with a screenshot:
As you can see, the problem is that the point suddenly changes to a comma when I look up an ID in the UserForm.
Before recalling Infos, I am saving all Information rather straightforward:
with ws
Range("BH" & lastRow).value = Me.payinfoOnTime
Range("BI" & lastRow).value = Me.payinfo30
Range("BJ" & lastRow).value = Me.payinfo60
Range("BK" & lastRow).value = Me.payinfo90
Range("BL" & lastRow).value = Me.payinfo90more
End with
Recalling the respective info for a searched ID is done by:
Set FoundRange = ws.Range("D4:D500").Find(What:=Me.SearchSuppNo, LookIn:=xlValues)
With ws
Me.SEpayinfoontime = FoundRange.Offset(0, 56)
Me.SEpayinfo30 = FoundRange.Offset(0, 57)
Me.SEpayinfo60 = FoundRange.Offset(0, 58)
Me.SEpayinfo90 = FoundRange.Offset(0, 59)
Me.SEpayinfo90more = FoundRange.Offset(0, 60)
end with
The Problem is that later calculations for scores are depending on those textboxes and I constantly get an error, unless I always manually change the commas back to points.
Any ideas how I can fix this?

The line:
Me.SEpayinfoontime = FoundRange.Offset(0, 56)
is in fact:
Me.SEpayinfoontime.Value = FoundRange.Offset(0, 56).Value
When you populate an MSForms.TextBox using the .Value property (typed As Variant), like you implicitly do, and providing a number on the right side, the compiler passes the value to the TextBox as a number, and then the value is automatically converted to string inside the TextBox.
Exactly how that conversion happens does not appear to be documented, and from experiment, it would appear there is a problem with it.
When you freshly start Excel, it would appear assigning .Value will convert the number using the en-us locale, even if your system locale is different. But as soon as you go to the Control Panel and change your current locale to something else, .Value begins to respect the system locale, and changes its result depending on what is currently selected.
It should not be happening and I would see it as an Excel bug.
But if you instead assign the .Text property, the number is converted to string using the current system decimal dot, and that conversion happens outside of the TextBox, because the compiler knows .Text is a string, so it converts the right-hand side number to string beforehand.
So in your situation I would:
Make sure I always use the .Text property explicitly:
Me.SEpayinfoontime.Text = ...
Make sure I explicitly use the correct kind of functions to convert between text and numbers:
Me.SEpayinfoontime.Text = CStr(FoundRange.Offset(0, 56).Value)
MsgBox CInt(Me.SEpayinfoontime.Text) / 10
although this step is optional and represents my personal preference. Given that it's a string on the left side of the assignment, VB will use CStr automatically.
Go to Excel's settings to make sure the "Use system separators" tick is set.
Check what locale is selected in the Control Panel - Language and Regional settings.
If it is not En-Us, I would select En-Us to make sure the decimal separator is a dot there.
Restart Excel.

Related

Odd behaviour by automatically changing color of certain characters in a cell

I'm facing a odd behavior by applying different colours within one cell via VBA.
In my case there are hundrets of cells within one column, showing different work-packages.
My vba code exaclty does what it should do, by coloring identified strings (respecively work packages) via looping through the cells and identifiying each work package via RegExp.
Here there is one extract that is doing the coloring job:
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = suchmuster
If .test(objWks_myTable.Cells(row_myTable, 20).Value) Then
Set RegMC = .Execute(objWks_myTable.Cells(row_myTable, 20).Value)
For Each RegM In RegMC
objWks_myTable.Cells(row_myTable, 20).Characters(RegM.FirstIndex + 1, RegM.Length).Font.Color = vbOrange
Next
End If
End With
The issue appears as soon as I double click the cell after my makro run.
Then without any recognizable pattern, some characters are shown in a different color (mostly not only one character but a connected bunch of). In the picutre, the first cell shows the colours after my vba run, the second cell shows how it will immediately look like, if i double click it.
If I leave the edit mode via Escape, the original vba set colors will stay, If I leave the edit mode via Return, the undefined changes happen.
There are no formats nor format conditions set within the cells.
I really need somebodys help here. Would be great to find a solution!
Many Thanks !
This picture should show the issue:
Picture of the issue
I've found the issue.
First I tried also Instr instead of using a RegExp but the issue didn't disappear.
So I was investigating in my code that writes the strings into the cells.
And within that code I did the following:
dummy = dummy & " # " & z_trim(ctrl.Caption) & vbCrLf
ActiveCell.Value = dummy
The issue is because of vbCrLf
If I write the strings into the cells the following way, the changes within my coloring run are fixed, there is no change by entering the cell in edit mode:
dummy = dummy & " # " & z_trim(ctrl.Caption) & Chr(10)
ActiveCell.Value = dummy
Picture of fixed issue
It works, so I'm fine. But still interessted, why vbCrLf is causing such confusing thing?

Comparing Textbox value to cell value

I programmed a communication tool for the production floor. This tool will register what they have done, who has done it and on what time.
The following should check whether the textbox value equals the value in the worksheet or if the textbox (textbox is TextTools1) is empty. If this is true, then nothing should happen and the thus the value of the textbox is gonna stay the same.
If the textbox is not empty or is not equal to what has been previously saved in the worksheet (thus the value has changed), then it should be registered which operator has done it and what date and what time.
It works when the textbox is empty, but when the value of the textbox has stayed the same (thus TextTools.value=ActiveCell.Offset(0,23).value (Correct)) it still adds the operators name, date and time.
Something is going wrong when trying to compare the textbox value and the cell value, but cant put my finger on it.
Sheets("Checklist & overdracht").Visible = True
Sheets("Checklist & overdracht").Select
If TextTools1.Value = Range("AZ1").Value Or TextTools1.Value = Empty Then
Sheets("Checklist & overdracht").Select
rowloc1.Value = ActiveCell.Row
ActiveCell.Offset(0, 23).Value = TextTools1.Value
Else
Sheets("Checklist & overdracht").Select
rowloc1.Value = ActiveCell.Row
ActiveCell.Offset(0, 23).Value = TextTools1.Value & " " & "(" & cboOperator.Value & " " & Format(DateValue(CStr(Now)), "short date") & " " & Format(TimeValue(CStr(Now)), "hh:mm") & ")"
End If
Edit; changed it to the code above. I tested this in another userform (and used f8) and it works brilliantly, but when I put in the userform that will actually run this code, than it doesnt have the same result...
Edit2; So apparently something goes wrong with Range(AZ1).Value reference. Because when I enter a random value instead of the range and then run the code, it does work. Is there a different way of referencing?
Ok based on your comments
Stop using active cell when code from a user form is communicating to the compiler what sheet is what. You need to fully qualify what sheet you are using. Im not entirely sure where in the code the active sheet is being set but I am fairly certain the answer is never. Another reason selecting and referencing .ActiveWhatever is bad is a cardinal sin of vba is interacting with the actual application object instead of doing everything in memory. It bogs everything done and performance suffers considerably. When you start writing pretty dense stuff then you will inevitably suffer from issues where the compiler gets confused as to what thing it should be looking at and you'll have a grand ol' time of troubleshooting that nonsense.
Also, it might be a good idea to check for more than just "=Empty". What if there is a null or empty string? I tend to check for:
.value = "" OR ISNULL(.Value)=True OR .Value = vbNullstring
this isnt real feedback though - tons of people have different ways of doing the same thing.
Try:
Thisworkbook.Sheets("YOURSHEETNAME").Range("YOURRANGE").Offset(0,23).Value = Someothervalue.
Let me know if youre still facing issues.

Variable that contains different value for each loop

I would like to download prices from the internet. The concept works, when I define symb as a constant value (e.g. K15). But now, I want to download data from different links, where the part symb changes according to the value of the cells G13 to G22 in my spreadsheet. (In other words, I want to go through each row from G13 to G22 - each containing a different value for symb - and download the data from the respective link).
I tried that with a simple loop, defining the variable symb in each one of the loops:
For i = 1 To 10
Symb = Worksheets("Futures").Range("G12").Offset(i, 0).Value
Set qt = querysheet.QueryTables.Add( _
Connection:="URL;" & "http://download.finance.yahoo.com/d/quotes.csv?s=" & Symb & ".cbt&f=sl1d1t1c1ohgv&e=.csv", _
Destination:=querysheet.Cells(5 + i, 1))
Next i
Obviously, it doesn't work like this. I assume that it is not possible to define a variable within the loop, is it? Can somebody give me a hint how I can make that work?
There's something worng with your Connection String. When I get rid of the .cbt in the URL string, it works. Or, you may have forgotten to include some letters, so debug it in your browser and get the Connection string correct and it should work.
You may also want to modify the destination, like so, and refresh the table:
Set qt = querySheet.QueryTables.Add( _
Connection:="URL;" & "http://download.finance.yahoo.com/d/quotes.csv?s=" & Symb & "&f=sl1d1t1c1ohgv&e=.csv", _
Destination:=querySheet.Cells(5, 1))
qt.Refresh
you could use an array like this
symb(1 to 10) as String
for i=1 to 10
symb(i)=cells(i,1)
next i

What does the number in the AddChart2 VBA macro represent?

I've use my Excel 2013 to record a macro in inserting a chart, a column-clustered chart in my case. In the view code option, it shows me a line of code as below:
ActiveSheet.Shapes.Addchart2(286,xl3DColumnClustered).Select
Please help me as I cannot understand what does the number 286 represent. I know the syntax of Addchart2 is:
expression.AddChart2(Style,XlChartType,Left,Top,Width,Height,NewLayout)
If I change the "286" to "285", the chart appears with a blue background. An error comes out if the number is 100.
Can anyone kindly tell me what does the number represent?
One can also provide only the ChartType and the application will use the default style.
Set oShp = ActiveSheet.Shapes.AddChart2(XlChartType:=xl3DColumnClustered)
oShp.Chart.SetSourceData Source:=RngDta
This picture shows the default ChartStyle for all ChartTypes (excluding StockHLC and StockVOHLC)
This won't directly answer your question, but it will help you figure out what is going on.
This is pure conjecture on my part, but I would guess it's an undocumented bitfield. As you may know a bit field is just a way to use a number. So image we have a Byte variable which can be 8 bits (or flags). So in a byte we can store up to 8 values.
Example: We have field called "DaysOpen" bits 1-7 mean the store is open on that day of the week. (We'll ignore the 8th bit.) So if the store is open M-F that would be binary 0111 1100.
Then you just convert that number to decimal and we see that it's 124.
That variable is a Variant so it could be anything from a Byte to Long meaning it could be storing up to 64 different flags.
As a side note (if you are interested) you can use bit fields like so:
Option Explicit
Public Enum DayFlags
'Notice these are power of 2.
dfSunday = 1
dfMonday = 2
dfTuesday = 4
dfWednesday = 8
dfThursday = 16
dfFriday = 32
dfSaturday = 64
End Enum
Sub Example()
Dim openHours As DayFlags
'Set the flags:
openHours = dfMonday Or dfTuesday Or dfThursday
'See the binary?
MsgBox Right$("00000000" & Excel.WorksheetFunction.Dec2Bin(openHours), 8)
'Notice the order is right to left. This is call endianness.
'You can check for a specific flag like this:
MsgBox IsOpenOnDay(openHours, dfMonday) & vbNewLine & IsOpenOnDay(openHours, dfFriday)
'You can add a flag like this:
openHours = openHours Or dfFriday
MsgBox IsOpenOnDay(openHours, dfMonday) & vbNewLine & IsOpenOnDay(openHours, dfFriday)
'You can remove a flag like this:
openHours = openHours Xor dfFriday
MsgBox IsOpenOnDay(openHours, dfMonday) & vbNewLine & IsOpenOnDay(openHours, dfFriday)
End Sub
Private Function IsOpenOnDay(ByVal openHours As DayFlags, ByVal day As DayFlags) As Boolean
IsOpenOnDay = ((openHours And day) = day)
End Function
Well , I had the same situation once, and those are basically chart styles. I tried to figure out the exact numbering but then i realized that recording was a much easier way of knowing the style numbers just as you have done here.
To answer you question, record macros to know which style you want to implement in your macros.
Just checking to see if 5 years later anyone has a better answer. I sure could use an enumeration of the chart styles; I don't like putting simple numbers in my code without some explanation as to what it means. Of course, I could use a comment, but if the numbers are documented, then that means they could change.
I found a partial list: https://learn.microsoft.com/en-us/office/vba/api/excel.xlcharttype
I'm sure these numbers, plus the bitfield variations as suggested by Pillgram above to control various other chart aspects, answer the question. The possible combinations are in the thousands, so a full list would be pretty useless. Recording is still your best bet.

Format a cell as arbitrary currency regardless of locale, using VBA

This is really bugging me as it seems pretty illogical the way it's working.
I have a macro to format a cell as a currency using a bit of code to obtain the currency symbol.
Here is the code involved:
Dim sym As String
sym = reportConstants(ISOcode)
'Just use the ISO code if there isn't a symbol available
If sym = "" Then
sym = ISOcode
End If
With range(.Offset(0, 3), .Offset(3, 3))
.NumberFormat = sym & "#,##0;(" & sym & "#,##0)"
Debug.Print sym & "#,##0;(" & sym & "#,##0)"
End With
reportConstants is a dictionary object with currency symbols defined as strings. E.g. reportConstants("USD") = "$". This is defined earlier in the macro.
When the macro runs it gets the ISO code and should then format the cell with the corresponding currency symbol.
When I run it in one instance the ISO code is "USD" - so sym is defined as "$" - but it still formats the cell with a pound sign (£). When I debug.print the format cell string it shows $#,##0;($#,##0) so, as long as I got my syntax correct, it should use a dollar sign in the cell. But it uses a £ sign instead. (I am running a UK version of excel so it may be defaulting to £-sign, but why?)
Any help greatly appreciated.
I just recorded a macro to set the format to $xx.xx and it created this: [$$-409]#,##0.00. Looks like the -409 localises the currency to a particular country; it works without it - try changing yours to .NumberFormat = "[$" & sym & "]#,##0.00"
Btw guess I read your question somewhat after posting ;) Excel is well influenced by the regional settings of your computer for currency, language, dates... Using numberformat can force it to keep the sign you require. if it is a matter of rounding up you can try to: On Excel 2010, go to File - Options - Advanced and scroll down to "When calculating this workbook" and click on the "set precision as displayed" and OK out. 
Try this: given your values are numerics/ integers/decimals....
Range("a2").Style = "Currency"
Or you can use format:
Format(value, "Currency")
Format(Range(a2).value, "Currency")
References:
http://www.mrexcel.com/forum/excel-questions/439331-displaying-currency-based-regional-settings.html
http://www.addictivetips.com/microsoft-office/excel-2010-currency-values/
(PS: I am on mobile, you may try these two links)

Resources