How to properly read a single Excel cell - vb.net

I've been looking up in Google in these past days but I still can't find a good answer to this one.
Currently, this is how I do it:
For Each cell In ws.Range(fromCol, toCol)
If IsNothing(cell.Value) Then Exit For
valueList.Push(cell.Value.ToString())
Next
But when it reads a cell whose assumed data type is Time, it returns a Double value. I try to parse that value but it's not the same as expected.
How can I properly read a single Excel cell with an assumed type of Time?

As per the comment suggesting the article,
.Text is a bad idea in the sense that it will give you just the displayed string in that cell. If you use TypeName on the cell's content, for example, it will always return string regardless of any datatypes the content might be. However, if you use .Value, it will return the actual datatype name of the content of that cell.
This can prove useful to you if you're using TypeName in a comparison for instance. It saves you using conversion functions.
Take this example:
Sub Test()
Range("A1") = "True"
Debug.print(TypeName(Range("A1").Value))
Debug.print(TypeName(Range("A1").Text))
End Sub
This Output is:
Boolean
String

Related

cannot get value from a cell in libreoffice 6.4.3.2 basic

I am new to libreoffice basic, i have experience with VBA but this libreoffice is different.
I just want to get cell value but it always return zero value to me while the actuall cell can be text or number.
Here is a partial of my simple code.
Sub test_moved()
Dim Doc As Object
'worksheet
Dim sh_village As Object
Dim sh_cbc As Object
sh_village = ThisComponent.CurrentController.getActiveSheet()
'sh_village = Doc.Sheets.getByName("VillageFinal")
'sh_village = Doc.Sheets(1)
Msgbox(sh_village.getCellrangeByName("B2").getValue())
Msgbox(sh_village.getCellrangeByName("B2").Value)
Msgbox(sh_village.getCellByPosition(1,1).Value)
msgbox("The process is completed.")
End Sub
Do we need to do prior task before start coding?
The code works correctly for numeric values. However, for strings, including strings that look like a number, it will display 0 because there is no numeric value.
What you probably want instead is:
MsgBox(sh_village.getCellRangeByName("B2").getString())
Also check out Format -> Cells -> Number to see how the data is displayed in the cell. And be on the lookout for a single quote at the front of the value in the formula bar (for example '42), because that means it is a string. Delete the quote to make it a number.
i have experience with VBA but this libreoffice is different.
Yes, LibreOffice Basic is a different language from VBA and the LibreOffice API is very different from the MS Office API. Knowing that will help you use it more effectively. If possible, avoid Option Compatible, because it won't fix most problems and will only muddy the waters.

Verify a variable contains Valid Range address in excel VBA

I have tried to get a value Range address value in to a variable.
searchWrd = InputBox("Please enter the column name of first word/token's", "Search String", "J1")
I need to verify the variable searchWrd contains a valid address or not. Also what should be the data type for the variable searchWrd
I'd go with
searchWrd = Application.InputBox("lease enter the column name of first word/token's", "Search String", ,,,,,8)
For more information read this:
https://msdn.microsoft.com/en-us/library/office/ff839468.aspx
Basically, the 8 at the end sets the input type to be a range. Note, that this will also allow you to immediately Dim searchWrd as Range.
You could try to verify the Text you get from the Inputbox by using a normal If-Then-construct. To get the correct data type we Need to know what should be possbible to type into the Inputbox. Normally i would try to get the Row/Column Number of the Row/Column the Search string is located at. Or, much better, to ask for the string it self and write the code to look up where it is located. So i only Need to check for spelling Errors and give a message that the string isn't found. It's better then asking for a range i think.

Get value from cell without transform in vba macros

I have an issue with vba macros. Cell contains value 941144280284022000000. But when try to get this value in macros, variable is equal
9.41144280284022E+20. Is it possible to get "real" value?
Thanks.
Here is an example:
Sub dural()
MsgBox ActiveCell.Text
End Sub
This will insure that long strings of numerals are not converted to numbers.
EDIT#1:
This assumes that the cell actually displays the long string of numerals. If the cell displays ####, that is what the sub will pick-up. If the cell displays 9.41E+20, then that is what my sub will pick-up.
My sub will not necessarily pick-up the contents of the Formula Bar.
Try a simple :
Dim myVar as Variant
myVar = CDec(Range("A1").Value)
If you wish to store a value that looks like a number (or is a number) but has more than 15 digits of precision, then you must either format the cell as text before entering the value, or prepend the value with a single apostrophe to indicate to Excel that the value is to be treated as text and not a number.
If you don't do this, then as soon as the value is entered, there's a good chance it will be altered by Excel. The trailing zeros in the example value mean this does not happen in this specific case, but try changing that last 0 to 1 and you'll see what I mean.
You enter: 941144280284022000001
Excel converts this to: 941144280284022000000
More reading: https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel

Excel VBA UDF that return value will override itself

Can I write a UDF in Excel VBA where the return value from the function will override the cell value from it is called from?
The function get information with a sql request. In this case it's only master data for example the item description. If the user will use this function in a worksheet in many cells excel will recalculate the cell value every time you change something. This has poor performance and normally it's only necessary to get the information one time and it hasn't to be updated in this case.
I thought to use application.caller.address method to get the address the function was called from but it seems it can't set the cell value for this address within the function.
So the return value of the function should override the original formula that run the function.
Is this possible
thanks for your help
No.
As you may have noticed Excel cells have multiple layers.
One is the "value". Another one the formula you can assign.
A funtions returns a value, therefore the return value only accesses this layer. So you cannot return a replacement for the formula cause it is on another layer.
A function differs from a sub in the return value, a sub does not return anything. Due to your behaviour of "one time usage" a sub will fit your need more than a function, because you dont want to return a value but to remove or replace certain content from cell (the formula).
However, this does not mean you cannot do this with a function - but still not with a return value. But you need to rewrite the whole formula on a data refresh if you would use such a function.
You may have missed a point that you make you laugh yourself I guess. Excel has such a thing natively. But it is not a function.
Copy your cells and paste them but use "values only".
Totally has the same effect.
Also in terms of recalculation... why not turn it off?
This would you not make to rewrite the function each time.

Validate entered cell value according to a given data type

I use an Excel macro to create new workbooks filled with data of given csv files. One column is open to user input of certain attribute values. These values must fit a datatype and a certain formatting to be accepted by another processing system, here are some examples:
Value A: String value formatted like "#"
Value B: Integer Value formatted "#"
Value C: Float value formatted "#.##0,0###"
Value D: Decimal value formatted "#.##0,0#"
Now i want to add a validation to check if a typed input value is ok for processing or has to be changed, examples:
a String value may not be entered in a Decimal field
negative values are not accepted for all number formatted fields
How do I set up this validation? I am quite new to VBA not shure about the best way to go. The possibilities I found so far:
Add a validation via Worksheet.Range.Validation, but I don't have any clue how to set up the Formula1 to check for correct values.
Go by Worksheet_Change, the problem here is that i create new Workbooks which apparently not contain the Worksheet_Change I wrote in my program code because it is a new workbook.
So what's the best way to go?
You can do quite a bit with data validation on the workbook side, without VBA. For example, for Value C, you could put in the formatting (Float value formatted "#.##0,0###") in the custom number format for that cell, then apply data validation to make sure only numbers are entered in a range you'd like.
Using Worksheet.Range.Validation is not very save because it is not triggered if user pastes data from clipboard.
Go for Workbook_SheetChange. Implement the validation there and save the workbook as your template.
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Debug.Assert (Format(Target.Value, "#.##0,0#") = Target.Value)
End Sub
Make sure all cells are formatted as text if you use this approch. Otherwise Target.Value will give you an interpolated value.
Then later open the template and import the cvs into it:
wb = Application.Workbooks.Add("path-to-template.xslm")
Application.EnableEvents = false ' You don't want to trigger change events during import
myimport(wb)
Application.EnableEvents = true