vba write numeric data as text into excel - vba

I am writing data into an excel spreadsheet. The data comes from an Access Database. Code like the line below works:
xl.cells(5,5)="joe"
but code like the line below does not:
xl.cells(5,5)="1/2CD438"
I get an error like "Application defined or object defined error"
I think Excel is trying to do a calculation, and the calculation fails. All I really want is the text string.
I've tried formating the column like
columns(1).NumberFormat="#"
, but it doesn't work either.
Any ideas?

Thanks for all the input. I had tried several of your ideas without success. As it turns out I was using variables to determine the exact row, column as:
xl.cells(NextRow, Col) = ars!PartNo
By simply replacing NextRow with an integer, the code worked. Replaced the integer in the test with NextRow, and the code ran. I suspect a misspelling or something, but couldn't see it looking at the code.
Thanks for the suggestions.

Related

Excel VBA Evaluate not working, getting a #VALUE error

I have a VBA formula that works when I use the ActiveCell.Formula2R1C1 function, which I used to test that I could get the result I want. This works as it should, giving me a comma delimited list.
ActiveCell.Formula2R1C1 = "=SUBSTITUTE(ARRAYTOTEXT(FILTER(VendSelect1,VendSelect3=LEFT(R[-7]C[-3],6))),LEFT(R[-7]C[-3],6) & "","","""")"
VendSelect1 and VendSelect3 are named ranges from a table in another tab
I am wanting to use the result of this formula as a string to use in a Data Validation list. The reason to go this route is the list will be dynamic based on a value that is entered in another cell, so the list will vary. I have the code for creating the Data Validation working, I just need to get the result of the above equation to be stored as a variable for that code.
I have tried using the Evaluate function to store the result but when I try to put that value in a cell to test that it is working, I get a #VALUE error in the cell. Is this just more complicated a formula than Evaluate can handle? Or am I doing something wrong? I am open to other suggestions to accomplish the same thing but I'm not a VBA expert and this has been the best thing I have found, so far, to accomplish this. Here is the code I have that is giving me the #VALUE error in cell D14.
Sub Test()
Dim FormTest As Variant
FormTest = Evaluate("=FILTER(VendSelect1,VendSelect3=LEFT(R[-7]C[-3],6))")
Range("D14") = FormTest
End Sub
I've been trying to get this to work for about 2 days and this seems to be the last obstacle to getting what I am wanting to do.
Thank you, in advance.

Is there a way to use VBA for Excel to output a formula to a specific cell in an Excel worksheet?

I am fairly new at programming. I feel like this should be a simple fix but I cannot find anything that works. I am trying to use a Select Case structure to write a different formula to a cell depending on the selected case. If I type:
Sheet1.Range("g10").Value = "=IF(SUM(F10)>0,SUM((F10-15)),"")"
I get an error:
Run-time error '1004'
Application-defined or object-defined error.
I can get it to work if I include spaces like so:
Sheet1.Range("g10").Value = " =IF(SUM(F10)>0,SUM((F10-15)),"") "
but then Excel puts it into the cell like text, not as a formula (it doesn't do anything).
I have tried a few different methods but have run into the same issue. Is it possible to do this?
I apologize if this has been asked and answered, but I wasn't able to find anyone referencing this specific problem.
You don't need to sum a single cell ie SUM(F10) Also SUM((F10-15)) is the same as F10-15.
Try this: Sheet1.Range("g10").Formula = "=IF(F10>0,F10-15,"""")" Also note, you needed to double the double quotes towards the end.
Note, you can do this on a range too like this:
Sheet1.Range("g10:g20").Formula = "=IF(F10>0,F10-15,"""")" and it is smart enough to increment the references for you for the 10 cells.
Wrong property. You need .formula not .value
worksheets("sheet1").range("g10").formula = "=IF(SUM(F10)>0,SUM((F10-15)),"")"
You should be able to type out the formula and then turn on the Macro Recorder and double-click on the cell with the forums, then turn off the Macro recorder and examine your code. That should give you what you want.

Error 1004 when using =AND(ISERROR) formula in macro

I'm recording a macro to automate some Excel reports and have encountered the following bug whenever I try and run an iserror(search) formula:
Run-time error '1004': Application-defined or object-defined error
I have two lists. The formula iterates through the first list and compares the values with those of the second list, hiding any matching values.
The formula in Excel is like this only with a wider criteria range:
=AND(ISERROR(SEARCH($B$3212,B2)),ISERROR(SEARCH($B$3213,B2)))
It works perfectly when I insert the formula directly into the spreadsheet cell however I get an error when I record and later run the macro using the same formula.
EDIT 2
I got the formula insertion to work through the macro but now I cannot filter the data as before, even when I do it manually without the macro.
Below is a link to a picture giving an example of the type of lookup I'm trying to achieve, previously it worked perfectly and removed all the rows which contained a string from the 'to remove list' now I cannot get it to filter at all. I've tried removing the macro after saving in notepad in case the file had become corrupted but it still does not filter as before. What could be causing this?
This is how the lookup works
Cell [A13] would contain the aforementioned ISERROR formula in this example.
This formula doesn't translate well to VBA in its current form. You should use the VBA Instr function instead of the worksheet function Search.
Function FindSubstring() As Boolean
Dim rngFindText As Range
Dim rngWithinText As Range
Set rngFindText = Sheet1.Range("B3212")
Set rngWithinText = Sheet1.Range("B2")
FindSubstring = InStr(rngWithinText, rngFindText)
End Function
Sub foobar()
Debug.Print FindSubstring
End Sub
You are asking Excel a question to tell you to find the contents of $B$3212 in B2 and to find if again.
Usually the SEARCH is used to find the contents of one thing in another, by using it again the AND statement you are asking it again ... and for what?
Hence the question does not make sense.
What I think you might be asking if just once and if there is an error meaning it did not find it there in this instance for it to return 0.
=IF(ISERROR(SEARCH($B$3212,B2)),0,SEARCH($B$3212,B2))
I figured this one out, the original 1004 error was caused by vba only partially recording the formula, the solution involved simply going into the debugger to find which line hadn't been translated correctly and editing that line. I then had to edit the formula so as to be able to filter out values acording to my criteria and ended up with a formula closer to this:
=AND(ISERROR(SEARCH("Value1",B2)), ISERROR(SEARCH("Value2",B2)))

Inconsistent recognition of ranges (No errors thrown)

This is code from Excel 2010. All of the code resides within the workbook itself. Information is gathered using internal forms and the code is run.
I have code that retrieves data from a spreadsheet and populates an object with that data. The row number is dynamic as it is dependent on the form input. The column is by the header, not the column number. The following code works perfectly but for two anomalies:
cTank.RowForTankSpecs = rNum
cTank.MP = .Cells(rNum, Range("MP").Column).Value
cTank.Form = .Cells(rNum, Range("formName").Column).Value
cTank.TankProcess = .Cells(rNum, Range("Process").Column).Value
cTank.Location = .Cells(rNum, Range("Location").Column).Value
cTank.TankName = .Cells(rNum, Range("Tanks").Column).Value
cTank.tankID = .Cells(rNum, Range("TankID").Column).Value
First:
The cTank.TankName is retrieving information from a column named "Tanks". That column does not exist. The actual column header is "Tank". But, it is retrieving the correct information. If I change the name to what it really is (Tank), it does not work.
Second:
When the cTank.TankID line is executed, I get the following error on the Range("TankID"):
Runtime Error 1004: Method 'Range' of object '_Global' failed
This one has the appropriate header (column header), but it is not recognizing the range.
I have tried simple things such as changing the order of the code, but it doesn't help. As earlier stated, the other lines work. Later in the program, information is gathered in the same manner but using another worksheet from the same workbook, and none of them are working. I've double checked that strings are strings and integers are integers, etc. I've double checked the column headers match the range names. Nothing seems to jump out at me.
I would appreciate any input you may have on the situation.
Thanks in advance.
Steve
Ok. Being pretty sure my code was correct, I went to the spreadsheet itself. For some reason it was recognizing only certain columns and it was recognizing one of them incorrectly. So I started highlighting the columns that worked and also the columns that didn't. What I noticed was that on the columns that were being recognized, that column header was displayed where the cell location is normally displayed whereas on the columns that were not being recognized, the cell location (i.e. A1, A2, etc.) for the header was being displayed and not the header title itself. The incorrect label was showing up for one of them. As it turns out, the mislabeled column was one that I had used for a form dropdown menu. So, I checked the name manager, and the ones that were working were listed. So anyway, using the name manager, I added named ranges using the headers. Now, when I select the columns, the column header(named range) appears in that window and now, the code works.
Thanks guys for your input. I really appreciate it.
Two things you can do:
Do not use use Range, but as it seems you are using names, use Names("Yourname").Referstorange.
OR
Make sure your names are set up correctly using the Name Manager in Data Ribbon.

Calculate a percentile using EPPlus

I'm trying to use either PERCENTILE.EXC, PERCENTILE.INC or PERCENTILE.
Looking at FormulaParserManager.GetImplementedFunctionNames() these are not implemented functions.
I wondered if I could set the formula and leave it to Excel to calculate. So far I've not got this to work and I get a #NAME? and "The formula contains unrecognized text". Merely clicking in the formula bar causes the formula to be calculated correctly.
Inspecting the internals of the Excel file I am creating (via EPPlus):
_xludf.PERCENTILE.EXC(B14:B113,0.95)
whereas in Excel I get:
_xlfn.PERCENTILE.EXC(A14:A113,0.95)
I think this is user defined function vs function. I've tried prefixing "_xlfn." to my formula string.
This is as far as I've got I think I either need to roll my own percentile calculation in code or manipulate the xml in the Excel file maybe.
Any help appreciated.
Doh! I spend all afternoon stuck, post a question here and then immediately suss the answer...
Anyway in case anyone is interested:
var row95 = percentile95RowLookup[profileKey];
var percentileRange = sheet.Cells[row, i, row+ profileCollection.Profiles.Count-1, i];
sheet.Cells[row95, i].Formula = $"_xlfn.PERCENTILE.INC({percentileRange.Address},0.95)";
With the important proviso that workbook.CalcMode is not Manual.