Writing numbers to cells as text - excel

I am using VBA to manipulate a dataset and ahve run into a problem; I need to write some values to cells but keep them as strings rather than numbers so later filters will work with other database data.
I was using Cell.Value = x which does the job but is there a way of getting it to write with a string?
I have a feeling this has a simple answer but my google-fu is weak.

Consider
1) Formatting the cell as text (available on a right click as 'Format Cells')
2) Clobbering the cell completely with Cell.Value = "'" & CStr(x)
I prefer (1) since it is separating data from presentation; always good programming practice.

Related

Excel 2010 Data Validation allow specific layout

I want to apply data validation to reference numbers, to force the following layout (ideally uppercase only):
XX_NNX-XX_NNN_NN-XXX
X = Numbers
N = Letters
Ex: 12_AB1-23_ABC_AB-123
The following custom formula allows all of it except for numbers - is there any workaround for this?
I don't want to use * since it allows for more characters than I want.
=COUNTIF(A1,"??_???-??_???_??-???")
You can choose AND to add a condition to the function you have already written. e.g. following shall test the positions which shall be numeric.
=AND(COUNTIF(A1,"??_???-??_???_??-???"),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0))
Notes: This is fairly basic approach and may need some tweaks if you have cases involving usage of decimals etc.
Edit: You can try below approach for checking upper case text in specified positions.
=AND(COUNTIF(A1,"??_???-??_???_??-???"),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0),INDEX(FREQUENCY(-CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),{-91,-65,0}),2)=7)
Edit2: This turned out to be tougher than I had imagined. Following formula works in DV for cell A1.
=AND(COUNTIF(A1,"??_???-??_???_??-???"),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0),MIN(FLOOR(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),65))=65,MAX(CEILING(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),90))=90)
But due to some quirk, Excel won't let me simply paste it. So I wrote a small code for the same which applies DV to cell A1 and surprisingly it accepts that same long formula through code. Make sure that you delete DV in the cell before you run this code.
With Range("A1")
.Value = "12_AB1-23_ADC_AZ-123"
.Validation.Add xlValidateCustom, , , "=AND(COUNTIF(A1,""??_???-??_???_??-???""),ISNUMBER((LEFT(A1,2)&MID(A1,6,1)&MID(A1,8,2)&RIGHT(A1,3))+0),MIN(FLOOR(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),65))=65,MAX(CEILING(CODE(MID(MID(A1,4,2)&MID(A1,11,3)&MID(A1,15,2),ROW($A$1:$A$7),1)),90))=90)"
End With
Once in there, you can get it in any other cell by simply doing copy >> Paste Special >> Validation.
For clarity, I use Excel 2016.

.FormulaR1C1 containing variables with values read from files

The code lines
.FormulaR1C1 = "=IF(R1C1="&Chr(34)&text&Chr(34)&",1,0)"
.FormulaR1C1 = "=IF(R[-3]C[2]="&Chr(34)&text&Chr(34)&",1,0)"
are examples of the usual manner to insert R1C1 formulas in target cells when the addresses of the target cells are already known. No problem with that.
BUT...I can't find the way to devise a general R1C1 formula that can be used to do the job when the addresses of the target cells aren't previously known, but they are read from different text files instead, and both, rows and columns, may vary from one occasion to the next, getting inserted by means of loops. The following code lines can give an idea of what I'd like to have in a text file to be read, inserted in a cell and work properly:
"=IF(R[-"&varRow&"]C["&varCol&"]="&Chr(34)&text&Chr(34)&",1,0)"
"=IF(R"&varRow&"C"&varCol&"="&Chr(34)&text&Chr(34)&",1,0)"
In other words, I can't figure out how to use variables for the numbers of rows and columns in the examples given above. I asume such a possibility exists, but I have ran out of ideas on how to implement it. I've implemented some, but I've just gotten the code to be inserted as the value for the cells or the #NOMBRE(#NAME) error.
What is a solution to this problem?
I am not able to "replay" your issue...or I understood it wrong.
If I use this code:
Range("C2").Select
Dim varRow As String
Dim varCol As String
varCol = 2
varRow = 2
Range("A1").FormulaR1C1 = "=IF(R[" & varRow & "]C[" & varCol & "]=" & Chr(34) & Chr(34) & ",1,0)"
The right formula appears in cell A1 and does its job.
To write this in a file, just put the formula string as it is in a string variable and write it to a file.
Scott, SJR, and anyone reading this post.
Apologies in advance for the length of this post, but I think that the matter deserves it.
I have managed to solve the situation regarding the FormulaR1C1 format when it is to be loaded from a text file. However, I'm not totally sure of the why and the how involved in the analysis and the solution. Maybe you can give a thorough explanation about it.
The fact is that the solution (formula format) you have given, quite similar to the one given by Microsoft and similar to the result obtained when recording the macro in entering the procedure by hand, when entered as plain text in a text file and then read from it and placed in a cell just doesn't give the result expected. An example of the original data in a text file:
22_2_|"=IF(R[" & varRow & "]C[" & varCol & "]=" & Chr(34) & varValue & Chr(34) & ",1,0)"
"22" would be the row number (varRow) and "2" the column number (varCol).
I tried every different logical possibility that came to my mind over and over, all of them with similar results: failure. Then I decided to forget logic and try random thoughts.
First thing I did on this new trail was to revise the original idea: use a general formula exclusively with variables in it. I realized that I was making a stupid mistake giving the value for the variable -for instance, the column and row number- and right next to it placing the variable in the formula at the same time. Why to do it that way? Why not to place the numbers for the row and column directly in the formula? After all, the formula should work the same all the way.
An example for this new approach could be:
"=IF(R[number]C[number]=" & Chr(34) & varValue & Chr(34) & ",1,0)"
I did it this way and tested it, with dissapointing results, similar to the ones obtained at first.
Then I thought about the quotes used for the formula format. Could it be possible that the reason for the problem might have to do with them? Well, there was only one way to find out. So I tried it this way, then this other way, an other..and other...and then...EUREKA!...This is what I got, that finally works:
=IF(R22C2="value",1,0)
As you may notice, the final formula ends up having no variables at all. That was a stupid idea on my side, considering that the data is going to be obtained from a text file. So, forget the variables. BUT...and this is a very important "BUT"...
Notice what has happened to the quotes. The only ones remaning are the ones that enclose the value that is to be compared. All the others have dissapeared. And this is the only way in which the formula, when read from the text file and inserted in a cell, ends up as a functional formula in the cell, and not as the value for the cell or as a "#NAME?" error. And now, a very important question: WHY? My answer for it: I have no idea.
I must suppose -and that's the most I can do at this moment- that the fact the formula is being read from a text file and inserted as text in the cell is handled by Excel in a "certain way" that already includes -behind curtains- the necessary quotes in the internal works of the worksheet. So, if you previously include some quotes, the formula ends up having an excess of them and the final product is not the one expected. Might that be it? Who can tell? Well, what matters to me is that, as strange as it may look, it now works as I wanted it. Give it a try yourself, and then tell me.
Well, pals, that's it. And thanks a lot to all for your kind and timely help.

Working with variables in an Excel formula

I am aware that
Cells(16, 2) = "=TEXT(42831,""dd-mmm-yy"")" 'DISPLAYS 06-Apr-17 IN CELL B16
The macro I'm working on needs the Date Serial Number, namely 42831, to be replaced with a variable:-
Dim lngDateSerialNo As Long
lngDateSerialNo = 42831
So now I have assigned 42831 to the variable, lngDateSerialNo.
It's not really relevant here but just to say that this variable will be updated during run time to give me a desired sequence of dates spaced one week apart.
I am also aware that
Cells(18, 2) = "=TEXT(" & lngDateSerialNo & ",""dd-mmm-yy"")" 'displays 06-Apr-17 IN cell B18
and to be fair I needed help with the above line of code.
OBJECTIVE
To try an understand what exactly the Ampersand is doing - apart from giving me the result I want!
Being relatively inexperienced in VBA, my understanding of the Ampersand is that it is a Concatenation operator and doesn't appear to have any other function in life.
Question 1
Could someone out there please give me an understanding as to why that line of code works so well?
Question 2
Purely academic, but if indeed the Ampersand is a concatenation operator, can the CONCATENATE formula be used in place of the ampersand?
my understanding of the Ampersand is that it is a Concatenation operator and doesn't appear to have any other function in life
Basically yes, unless you want to also consider the & being used as a type specifier for Long:
Dim a& ' declares a As Long
Could someone out there please give me an understanding as to why that line of code works so well?
Because that is the way to write this kind of code.
The only change you can potentially make is to replace the & with a + which works like & if both arguments are strings, but you shouldn't do that because & expresses the intent in the clearest way.
Purely academic, but if indeed the Ampersand is a concatenation operator, can the CONCATENATE formula be used in place of the ampersand
No, because that particular & is a part of the VBA syntax. You are building a string in VBA, it does not matter at this point that the string contains an Excel formula. VBA does not have a CONCATENATE function so you can't use it in place of the & when building a string in VBA.
However the & is also used for string concatenation in the Excel formula syntax, and if you were to build a formula with a & inside the double quotes, not outside, you could replace it with CONCATENATE, because now it's the Excel syntax where CONCATENATE exists.

Comparing two sets of cells within a row and highlighting same-row duplicates in Excel

I've got a somewhat specific task I'm trying to accomplish in Excel that appears to be beyond my depth. I've got a dataset with two five-word lists per each row/observation, like this example:
What I'm hoping to accomplish is to highlight all of the words that are in both 5-word lists within a single row. The amount of overlap between these two five-words lists varies from one row to the next. And I'm not concerned with identifying any duplicate entries across different rows. That is, it'd be great if it's possible to create a macro that would give this:
I've searched quite a bit on this site and using google to figure out how to create a macro to do this. I've found a number of similar macros, but every one that I've found is geared towards identifying all of the duplicates between two entire sheets, or two entire columns, or something similar, which doesn't quite match what I'm trying to do. Based on the macros I have been able to find, I get the sense that doing what I want should be possible, but I don't know enough about visual basic to edit the macros I've found to suit my needs.
If it's possible to program a macro to do this, it'd save me quite a bit of time, since otherwise I'm looking at doing this duplicate-identification manually for two current datasets that I have (each with 150-200 observations), plus I plan on collecting data in the future that would require this same procedure. Beyond that, any macro that's capable of helping me here may be able to help others with similar needs.
Thanks in advance for any help you're able to provide!
Try conditional formatting.
Select "table 2" (e.g. I2:Mn where n is the last row) with I2 (upper left corner) being the active cell. Then use this formula:
=OR(I2=$C2:$G2)
I think using Conditional Formatting is maybe a simpler solution but one way to do this using VBA is as follows:
Sub HighlightDuplicates()
Dim masterList(), highlightList(), rw As Long, col As Long
masterList = Range("C1:G150")
highlightList = Range("I1:M150")
For rw = 1 To UBound(masterList, 1)
For col = 1 To UBound(masterList, 2)
If highlightList(rw, col) = masterList(rw, col) Then
Cells(rw, col).Offset(0, 8).Interior.Color = vbRed
End If
Next col
Next rw
End Sub
Here we read both lists in as arrays and then iterate over them to check for matches.
The Offset(0, 8) is a bit of a magic number (yikes!) which gets the correct cell highlighted based on your layout.

Is there any way to speed up excel comparision in VBScript?

I first made a VBA script to compare two excel files. Then optimized it using Variant as said in this question. But then, I changed it to VBScript later. Here the method said above doesn't seem to work.
Are there any other better ways to speed up the process? Especially for large files.
My core code is as follows:-
For Each cell In objxlWorksheet1.UsedRange
If cell.Value <> objxlWorksheet2.Range(cell.Address).Value Then
'fill the color in the cell if there is a mismatch and Increment the counter
objxlWorksheet2.Range(cell.Address).Interior.ColorIndex = 3
counter=counter+1
End If
Next
It depends on what it is that you are comparing. If you have two sheets with similar tables of data it would be easier to use formulas instead of VBA code. Just create a new worksheet and enter a formula like this: =Sheet1!A1=Sheet2!A1 Then you can use Ctrl-Find to search for False
Or if you can copy the data on one sheet side-by-side, you can use conditional formatting to highlight values that are different.

Resources