Excel VBA Time Format as decimal with Combobox - excel

Very basic, and very annoying, I have searched solution for many hours with no help...
Problem: I'm populating Combobox from named range, range is list of times (formatted as time :-), Combo seems fine, drop-down shows my times as they should be, but when selected time is formatted as a decimal number...
Here is the code (ripped down to bare minimum):
Private Sub UserForm_Initialize()
ComboBoxTime.RowSource = "Help!Time"
End Sub
"Help" is name of worksheet containing named range "Time"I have tried formatting different ways with no luck...
ComboBoxTime = Format(ComboBoxTime, "hhmm")
Here is link to sample. http://www.equstom.fi/dateproblem.html
(And yes I need to populate from named range, instead for each loop, and I will set .value with code, Whole document is actually quite complex, but I included just The problem part...)

Try something like this:
Private Sub ComboBox1_Change()
With ComboBox1
.Value = Format(.Value, "hh:mm:ss AMPM")
End With
End Sub
HTH!
Edit
This is what I see when leaving your combo. The time display works OK.
Edit 2
Found the error "invalid property":
You must set "Match Requiered" to FALSE in the combo box. If you consider that it should be "TRUE" you will have to validate by hand ...

The problem is named range I'm using, when values are formatted as time it won't work. I got it to work if values were Text! Problem has something to do with excel being in Finnish and VBA in english...
I added second column next to range which copies text values to this named second range formatted as time. Quick and Dirty! (Thanks for your input Belisarius)

Related

Printing out ActiveCell value on VBA

I'm trying to make a button which on click will print out the value of a cell as a string and not the appearance of the cell itself (if that makes sense) using the .PrintOut method in VBA. That cell is the active cell, whose value I set based on the cell next to it. Here is my code:
Sub Graphic2_Click()
Dim MyNumber as Integer
MyNumber = ActiveCell.Offset(-1, 0) + 1
ActiveCell.Value = MyNumber
ActiveCell.Printout
End Sub
I also tried MyNumber.PrintOut but I get an "Invalid Qualifier" error.
Am I missing out something too simple?
Please, try the next code. It use a temporary 'helper cell' where the format to be pasted (and recuperated after printing out):
Sub Graphic2_Click()
Dim helperCell As Range
With ActiveCell
.value = CLng(Offset(-1, 0)) + 1
Set helperCell = .Offset(1) 'it may be any cell to temporarilly be used
.Copy
helperCell.PasteSpecial xlPasteFormats
.ClearFormats
.PrintOut
helperCell.Copy
.PasteSpecial xlPasteFormats: helperCell.ClearFormats
End With
End Sub
To literally print just the contents of the cell:
Clear number formatting for the specified cell
Autofit column width for that column
Turn off gridlines
Turn off row and column headings
Set print area to the single cell, dismissing any warnings
Print out the active sheet
Each of these are straightforward to do in VBA, and probably straightforward to research on SO anyway.
You may also consider a mechanism to return the changed settings to their initial states afterwards. This would involve pushing (storing) the initial state to a variable or variables first, and popping (restoring) it back afterwards.
Explanation:
The VBA method .PrintOut is something you do to a worksheet, not a cell or its contents. Therefore, to get what you need, you need to set up the worksheet for printing so that the only thing that will appear is the contents of your chosen cell. This is what the above steps do.
For more information about the .PrintOut method, see:
https://learn.microsoft.com/en-us/office/vba/api/excel.sheets.printout
Or, to continue what the OP tried:
You could try something like:
ActiveCell.Formula = Range(ActiveCell.Offset(-1,0)).Value2 + 1
If this does not work, try:
ActiveCell.Formula = Range(ActiveCell.Offset(-1,0).Address).Value2 + 1
Or try these without the + 1 on the end, to verify that the rest of the formula is working the way you want it too. As mentioned, you may get a type mismatch issue causing an error if you don't trap first for whether the referenced cell contains a number.
.Formula in this example is how I am setting the content of the cell, and it can be used even when setting a value not necessarily literally a formula. You could use Value instead if you prefer.
.Value2 is a robust method of extracting the evaluated content of the source cell, as a value instead of as a formula.
The PrintOut method is to print a worksheet, not a range or single cell.
Note: This answer is not tested, as I am not near Excel right now.
Also... it's possible that there could be much simpler ways to do what you are trying to accomplish. Could you provide a bit more detail about the context of what you are trying to do.

TRIM aligns dates to the left

Problem
While writing this post, I realized what the issue was and fixed it. However, after spending too much time on this, I still would like to know if this is the best way to go about this.
In a worksheet I'm applying a macro to I have a column where some cells contain text, others contain dates (DD.MM.YYYY). Excel automatically aligns text to the left, dates to the right.
I've run into the problem of sometimes having trailing spaces in this column. So I used a for-loop with TRIM to make sure there are no leading or trailing spaces. It worked, but all dates are now aligned to the left, whereas before they were aligned to the right. When I double click into one of those cells and then select another cell, the date snaps back to the right (which is what I want), even though I haven't done anything to the cell.
Fix
It took me way too long to realize (or read attentively) that TRIM is for strings.
I noticed before running the macro: Dates are automatically aligned to the right, but in the ribbon, in "Alignment", there's no option for horizontal alignment selected. If I do so manually and align the dates to the right and then run the macro, the dates stay to the right.
When checking VarType before running the macro, I get 8 for the cells with text and 7 for the cells with dates, as expected. After running the macro, however, I get 8 (meaning string) for both. After double clicking into a cell with date and deselecting it, VarType is 7 again. In the Excel ribbon it always says that it's a Date (before and after the macro), so Excel seemingly doesn't show me what VBA tells me.
My workaround now is this: Before applying TRIM, my macro checks the VarType of the cell and if it is 7, it does nothing since the trailing spaces only have been a problem where users enter text. (Alternatively, I could align the dates right and let TRIM run over all cells)
This is fine, but is there a better way to do this? Does using TRIM on dates have the potential to screw something up? I'm trying to learn something from this.
Code
For good measure, my sample code, with the fix included.
Sub Test()
Dim ws As Worksheet
Dim searchRng As Range
Dim cell As Variant
Set ws = ActiveSheet
With ws
Set searchRng = .Range("A1:A100")
For Each cell In searchRng
If VarType(cell) = 7 Then
'Date -> Do Nothing
Else
cell.Value = WorksheetFunction.Trim(cell.Value)
End If
Next cell
End With
End Sub
For your question, I have do some testing, and my result is quite different compared to you, is it because excel version?
I have a data in A1 by put spacing in front of the date as below:
By executing the following function, the first typename was string, however after remove the spacing it end up typename date, I think it is not necessary to check the type on your solution?
Sub tt()
Debug.Print TypeName(Sheet1.Range("A1").Value)
Sheet1.Range("A1").Value = Trim(Sheet1.Range("A1").Value)
Debug.Print TypeName(Sheet1.Range("A1").Value)
End Sub
So it mean your code can be simplified on the loop as following and still produce the same result, it doesn't matter it is aligned to right:
For Each cell In searchRng
cell.Value = Trim(cell.Value)
Next cell

Excel VBA - Convert string entered in user form to number

I have an excel user form into which the user enters numbers, when those numbers are entered into the spreadsheet they appear with the notification that this is a number stored as text. =SUM(H6:H13) shows a zero result.
I have tried NumCrtn = cLng(NumCrtn) - doesn't change the cell to a number, formula still shows zero.
I have tried NumCrtn = Val(NumCrtn) - doesn't change the cell to a number, formula still shows zero.
I have tried copy and paste.special to a value and that doesn't change it to a number either.
Don't know what to do.
Help!
Try this one:
With Range("H6:H13")
.NumberFormat = "0"
.Value = .Value
End With
Edit:
Another solution. Building on Pradeep Kumar's suggestion which deals with preparing your range before you enter the data, Change your code to something like this
Private Sub UserForm_Initialize()
Dim aCell As Range
Range("H6:H13").NumberFormat = "0"
'This is to cater for any previous values if filled in
For Each aCell In Range("H6:H13")
aCell.Formula = aCell.Value
Next
End Sub
Private Sub CommandButton1_Click()
'Entering value for H6
Range("H6").Value = TextBox1.Value
End Sub
Range("H6:H13").NumberFormat = "#,##0"
It is not a VBA solution, but an ordinary Excel solution.
Do like this
Select the column
Select Data - Text to columns
Quite often the default settings will do and you can click Finish. Otherwise you
will have to make sure that the result is just a "General" column
A macro doing just this would look something like this:
Columns("A:A").TextToColumns
There's a lot of parameters to the TextToColumns method, but it should work fine with default values only (i.e. no parameters).

Automatic Text Capitalization Excel VBA

I'm currently trying to write a macro based on sheet change, where the letters in a table column are automatically converted to upper case. So, for example, if I entered "abcde-12345-678" into a cell, it would automatically correct to "ABCDE-12345-678". After doing some digging, I found some code that has worked for some people, but I'm having trouble tweaking it to suit my needs.
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("E:E")) Is Nothing Then Exit Sub
Application.EnableEvents = False
Target = UCase(Target)
Application.EnableEvents = True
End Sub
There are two things that I would like to address. The first being, that this code isn't currently working for me. I have it in the correct location according to the author (located in the Sheet1 object). Are there any ideas as to why this isn't working?
The second is that I would like to modify the code to refer to a table column rather than a range. For example, I've tried changing the second line of the above code to the following (the name of my table is ReviewTracker, and the column I'm interested in is Product Number):
If Intersect(Target, Range(ReviewTracker[[#Headers],[Product Number]])) Is Nothing Then Exit Sub
This returned a compile error "Expected: list separator or )". So there is obviously something wrong with it, but hopefully it might help illustrate what it is I'm trying to accomplish.
Thanks in advance for any help on the issue.
-Sean
First. You can have events disabled due to lots of reason. Let's make it sure that events are on which you can do as follows:
go to VBA Editor >> open Immediate Window >> write there: Application.EnableEvents = true >> press Enter
Second. To check if intersection match appropriate column within you ListObject table you need something like this:
If Intersect(Target, Range("ReviewTracker[Product Number]")) is Nothing Then
assuming that ReviewTracker is table name and Product Number is table column. You don't need #Headersas it will refer only to header row.
What UCase does is converting all the characters in a given string into upper case and thus you can apply it to any Range.Value. Worksheet_Change is called every time the value of a cell has changed and thus is a good place to put your code. But the way you are using to refer the table is wrong. The code your posted adapted to your requirements:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Sheet1.ListObjects("Table1").ListColumns(1).Range) Is Nothing Then Exit Sub
Target.Value = UCase(Target.Value)
End Sub
It converts into upper caps any string input in the first column of Table1 in Sheet1. It has to be placed in the Sheet1 object file (in the VBA Project explorer: Sheet1 (Sheet1) inside the Microsoft Excel Object folder). Adapting it to your actual conditions is straightforward.

Performing named cell additions in EXCEL VBA

I have a cell that is named DATA_FIELD_NAME and I would like to use it in the following way:
Private Sub LockCells(iNumberOfDataColumns As Long)
ActiveSheet.Unprotect
ActiveSheet.Cells.Locked = False
ActiveSheet.Range("DATA_FIELD_NAME:DATA_FIELD_NAME+iNumberOfDataColumns").Locked = True
ActiveSheet.Protect Contents:=True
End Sub
Essentially I would like to lock the range of cells starting from the DATA_FIELD_NAME cell horizontally to DATA_FIELD_NAME + n.
However this doesn't work. Could someone please tell me the correct syntax or an alternate method?
I'd try this:
ActiveSheet.Range("DATA_FIELD_NAME").Resize(1, iNumberOfDataColumns).Locked = True
Here is a reference on Range.Resize Basically it changes the amount of cells you are dealing with based upon the current range. In what I gave you, it changes to 1 row, and iNumberOfDataColumns columns.
I just wrote this in SO, not tested in XL, so it might contain typos, but this should work:
With ActiveSheet
Range(.Range("DATA_FIELD_NAME"), .Range("DATA_FIELD_NAME").Offset(0,iNumberOfDataColumns)
End With
The idea is to combine Offset(rows, cols) with to use the Range(range1, range2) syntax.
Alternatively, you could be a dynamic range name as explained here.

Resources