VBA - Sum Cells with the 'Number Stored as Text' error - excel

In Excel 2010, I am writing VBA to take the SUM of a range of filtered values, and store that result into a variable. The code looks like this:
With Sheets("Output")
.Range("$A:$ZZ").AutoFilter field:=ColIndex(AB), Criteria1:="x"
y = Application.WorksheetFunction.Sum( _
Range(Cells(2, "AC"), Cells(10, "AC")).SpecialCells(xlCellTypeVisible) _
)
This does work, but only when I have manually toyed with the data. When I try to use this formula on my data set unedited, I get a blank result. The problem seems to lie with the data when unedited.
Each number gets the Number Stored as Text (NSaT) error. Changing the type from Text to General causes nothing to happen. I have to open the cell for editing, and then remove focus from the cell for the type to kick in. After that, I can change it back and forth from General to Text, and Excel immediately recognizes this and updates the cell. The Sum function will, at this point, recognize both General and Text field types as a number.
Is there a VBA solution for dealing with these NSaT errors? I have attempted to use 'NumberFormat' on the column, but it does not help. I have also tried manually copying and pasting the data again, even using the special As Value option, but it still has the NSaT error until manually toyed with.

Related

Display a checkmark for any value

Using the cell format Excel allows any value to be displayed as any predetermined character. For many years I have used this feature to display a checkmark but now the code below is giving me a headache.
With Rng
.HorizontalAlignment = xlHAlignCenter
.NumberFormat = """" & ChrW(252) & """"
With .Font
.Name = "Wingdings"
.Bold = True
End With
End With
Everything is in the same workbook:
There is an account, a journal of sorts. My code filters out entries for one subject and writes the result to a dedicated sheet. The account has a column with checkmarks of this type and they are copied correctly to the tab with the filtered data. From the filtered extract my code copies items into a third tab where the info is displayed in context. Data, values only, are transferred via an array. As a result of this method the destination tab receives and displays the cell values. The above code intends to format the affected cells to show a checkmark.
Everything works fine except that the font doesn't appear to be applied. The formatted cells do show Wingdings as applied font. The value is present and suppressed but instead of a checkmark it displays nothing.
The cell format is set correctly. Since it was present in the workbook before it's noteworthy that no new format was added. (The use of ChrW() is a legacy from a problem in forgotten years past. Chr() produces the same result in the circumstance.) I tried to set the font before or after the NumberFormat.
I found that my present version of Excel (365) doesn't seem to have a checkmark in its Wingdings. Surprise because it's there in the same workbook but I didn't find it in Symbols. Instead I found Chr(80) in Wingsdings2. Applied with the same code the cells display "P", with Wingsdings2 shown as applied font.
Of course I checked the formatting of similar cells in the account and the filtered copy minutely and discovered no difference. I also tried to format the final cells again, using the same settings, but they stubbornly look at me with a blank stare.
As a coup de grace I applied the same code above to the ActiveCell on a blank sheet in the same workbook and it worked beautifully, Bold and all. So, what might be different on the worksheet on which it doesn't work? Actually, that is my question here.
Rows are inserted one by one, filled cell by cell, and a different format applied to each before the value is written. But stepping through the code with F8 produced no revelations. I also tried to enable ScreenUpdating (normally turned off while the code runs) but no different result. So, why isn't the specified font applied correctly?
The cells do have two peculiarities. One is that they are the last ones in the row. The other is that all other cells in the row are merged. This leads to a Merge command being applied to the single cell. To show the measure of my desperation I added If Rng.Cells.Count > 1 Then Rng.Merge. Of course, it made no difference.

Preserve formatting while copying the content of a table cell in a word and pasting it in excel

I have a cell in a table with mix of strike through words and plain words (without strike through). I was able to extract those value from the table cell of a word document and put it in a excel document. However, when i put it in a cell in an excel document, it pasted as plain words alone without strike through effects. So, can you suggest some way to retain the strike through effect while putting it in an excel please? Below is the snippet of my code.
Range("I54") = ObjDoc.Tables(1).Cell(1, 2) --> This extract the values without strike through effect.
Not sure if this will work, but in VBA word if you do:
MsgBox (Selection.Font.StrikeThrough)
You will get -1 if striketrough effect is on, and 0 if not.
In Excel VBA, If you do something like:
msgbox (Range("I54").Font.Strikethrough)
It will return True/False depending if striketrough effect is applied to cell or not.
As far as I know, True=-1 so maybe your code will work if you do it like this:
Range("I54") = ObjDoc.Tables(1).Cell(1, 2)
Range("I54").Font.Strikethrough = ObjDoc.Tables(1).Cell(1, 2).Font.Strikethrough
But not tested. Probably you can do it in 2 steps like above.

How to insert a formula by macro?

The issue has been solved.
It would appear that when I made some changes to capture data a little while ago, I inadvertently broke the order of things. When the above bit of code was running, the [Date Out:] column was indeed empty, so Excel was reporting properly.
I've since reordered the input of formulas and now the sheet works correctly, with credit to #BigBen and #Michael Wycisk.
I created an Excel sheet to draw together the data from several other Excel sheets into one to keep track of a project.
I have a formula that works if it is written into a range of cells with the source data sheet open in the background. If I ask a macro to put it into the required cells as the main sheet opens then the formula fails. By 'fail', I mean the formula checks it's first column to see if data is present or not and then decides that the column is empty regardless, therefore falsely reporting 'nothing sent' if there is a date in the "Date Out" column.
Here is the line in question.
WSR.Range("ReportTable[Latest Portare Instance:]") = "=IFERROR(IF([Date out:]="""",""Nothing Sent"",IF(AND([Received by Serial:]="""",[Received by Asset:]=""""),""Not Received"",IF([Received by Asset:]<>"""",LOOKUP(2,1/('Stock Movement Archive Defra.xlsx'!Archive[Asset No:]=$J2),'Stock Movement Archive Defra.xlsx'!Archive[Location:]),LOOKUP(2,1/('Stock Movement Archive Defra.xlsx'!Archive[S/No:]=$I2),'Stock Movement Archive Defra.xlsx'!Archive[Location:])))),""Issue"")"
It's one of several formulas, all inserted the same way and the rest work. As far as I can tell the formula is being inserted correctly, just that this one stops at the first if statement.
For reference, I have tried changing the first 'if' statement to start IF([Date out:]<>"""", the formula then either states "Nothing Received" where there is no date or pulls the correct data if there is a date. Also tried changing the format of the "Date Out" column.
The formula looks fine for me. The only problem might be that you need to use the .Formula property after the Range object:
WSR.Range("ReportTable[Latest Portare Instance:]").Formula = "=IFERROR(IF([Date out:]="""",""Nothing Sent"",IF(AND([Received by Serial:]="""",[Received by Asset:]=""""),""Not Received"",IF([Received by Asset:]<>"""",LOOKUP(2,1/('Stock Movement Archive Defra.xlsx'!Archive[Asset No:]=$J2),'Stock Movement Archive Defra.xlsx'!Archive[Location:]),LOOKUP(2,1/('Stock Movement Archive Defra.xlsx'!Archive[S/No:]=$I2),'Stock Movement Archive Defra.xlsx'!Archive[Location:])))),""Issue"")"
To make sure that your formula is correct (you say it works fine when typed into the cell), you might type it into the cell, select the cell and then type ?ActiveCell.Formula into the Immediate Window inside the VBE (don't forget to check that the quotation marks are correct).

(MS EXCEL) How do I replace cells with formulas to its calculated value AUTOMATICALLY?

I am making a payroll program in Excel and one of my concerns is that the salaries of the employees are searched using the INDEX and MATCH or VLOOKUP function. The problem is if the salaries get updated in the future (e.g. a raise or changes in rates), all the previous entries that used the old salaries will be updated to the new salaries. This is a disaster and would make my entire program useless and inefficient. Therefore I need to automatically lock previous calculated cells after a certain time.
Edit: Note we do not want to do this manually such as copy pasting values only because almost all cells are connected to each other and one mistake by the encoder or if they forget to do this before updating a value, everything will be messed up.
No! Not copying and pasting, there's a simpler way. You want to convert the Formula property of a given cell (what's shown in the formula bar in Excel) into the Value property of the cell (what's shown in the cell on the spreadsheet). For a given range A1:B6 this would done by the statement
Range("A1:B6").formula = Range("A1:B6").value
But there's a quirk in Excel that you can run faster by accessing a Value2 property, so
Range("A1:B6").formula = Range("A1:B6").value2
The rest of the code is left as an exercise for the reader :-)

Excel VLOOKUP #N/A

What I am trying to achieve is matching two projects with eachother "Project No" in two tables, and return the "project name" in second table. When I do this I receive this error inside the cell error #N/A.
I have formated both tables into number value, but this does not solve the problem.
Anyone that has an idea what I can do in order to solve this problem.
Here is the first table (just a snapshot to give an idea).
Here is the second table (just a snapshot to give an idea).
The #N/A error indicates that Excel cannot find the value you've specified in the list in which you've told it look. When I run into this, there are a few things I do to troubleshoot:
1) Make sure both columns are in the same format.
You mention you've already done this (good job!) but sometimes formatting gets stuck in Excel. One thing you can do is to highlight each range and use the text to columns feature (under the data tab) to convert it all to the same format. Another option is to copy the range into Notepad or some other plain text editor and then copy it back into Excel to strip out any lingering formatting.
2) Double check your ranges.
Make sure your Vlookup is looking to the correct range, and make sure that range is locked (i.e. $A$1:$D$100 rather than A1:D100), or else your ranges are going to slide around as you move drag the formula down your table. If the range refers explicitly to a table address (e.g. Table1[#All]), then make sure every data point if validly within that table.
3) Make sure the range lookup parameter is set to FALSE
Range lookup is the last parameter of the vlookup, and determines whether the vlookup will find an exact match (set range lookup to FALSE) or a partial match (set range lookup to TRUE). Setting range lookup to TRUE can sometimes create errors like the one you've described. I always set it to FALSE by default unless I need specifically need to set it to TRUE.
4) Use the find and replace window to manually evaluate the formula
If everything looks correct, copy the value you want to look up and paste it into the find and replace window to search for it. If Excel can't find it and you can see it in your list, something is definitely wrong with the formatting or else your file may have some degree of corruption. If Excel can find the value, double check that it is within the range your vlookup is looking through.
If fist table is the one with vlookup formula and second is a source it may mean that such Project No. doesn't exist in your source table. Did you check that possibility?

Resources