Blank Fields Copied as #N/A - vba

I am working with an Excel 2003 VBA script that copies the content from worksheets in an external Excel file to worksheets in our own:
ThisWorkbook.Sheets(strTarget).UsedRange.Value = Workbooks(strFile).Sheets(strSource).UsedRange.Value
In a large number of blank cells, this function is posting #N/A instead of the blank values, which causes errors further down in the VBA code. This only occurs on some sheets, while others copy over just fine, sometimes by adding these values in extra rows and other times in extra columns. I have attempted to clear the error with IsNA to no avail:
If (IsNA(Workbooks(strFile).Sheets(strSource).UsedRange.Value)) Then
ThisWorkbook.Sheets(strTarget).UsedRange.Value = ""
Else: ThisWorkbook.Sheets(strTarget).UsedRange.Value = Workbooks(strFile).Sheets(strSource).UsedRange.Value
Is there a simple way to remove these #N/A values during the copy or even clear them after the fact?
Any other advise on how to handle this issue would also be greatly appreicated, as I'm not a VBA dev myself, but simply the lucky soul who got to pick this up when the only person with Excel and VBA experience left our team. Thanks in advance!

The problem comes when the ranges aren't the same size. You should resize appropriately:
With Workbooks(strFile).Sheets(strSource).UsedRange
ThisWorkbook.Sheets(strTarget).UsedRange.Resize(.Rows.count, .Columns.count).Value = .Value
End With
It's probably safer to clear the target sheet first using:
ThisWorkbook.Sheets(strTarget).UsedRange.ClearContents

Related

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)))

Find/replace conditionally formatted cells

I've been using a conditional format formula =OR(B2=B1,B2=B3) to highlight consecutive duplicates. I then use format painter to copy the formula to all columns in my excel table.
I have set up a button that will, amongst other things, copy a workbook into a new workbook. I now want to include the above formula in this macro. My final objective is to replace all of the cells found with this formula with an asterisk (*).
I first tried to just pop the formula into the macro as a starting point -
For Each sh In Destwb.Worksheets
With sh.UsedRange.FormatConditions _
.Add(Type:=xlExpression, Formula1:="=OR(B2=B1,B2=B3)")
.Interior.Color = RGB(198, 239, 206)
End With
Next sh
But this just makes a mess of seemingly randomly highlighted cells. I'm not sure where I've gone wrong. Even column B highlights are all wrong. Could the header in B1 affect this? It doesn't when I use the CF normally. How can I expand the CF into all columns uniquely?
Finally, how do I go about working a replacement of formatted cells into this formula? Or is there a quicker/easier way to meet this end-goal?
I didn't realise I could add custom text in that way. That's moved me a good couple of steps forward.
Taking Balinti's suggestion into consideration I've tried a workaround. I was making a couple of assumptions that turned out to be wrong. I have been able to enter the CF into the Array of data that I have in my original workbook. It's not as simple as putting it into a table, but by manually selecting the range in each column and inputting the CF I have made it work.
I also wasn't sure if the formatting would carry through to the new worksheet as I have used the Paste Special command to convert the array formula to values in the new sheet. It does, however, carry the formatting across which is very handy.
It's not the perfect solution for me but it appears to be working so far. I still need to test what happens when I change the date and get updated data. It would still be interesting to know if I can move this formatting into my macro though. Any tips?

Link from cell in other sheet shows 0 but other sheet shows data cant get past this

Spent hours searching for any mention of this but no luck. Maybe someone here knows the answer. I developed a large application in excel. sheet1 receives data from a Com server that just places it there. This has been working for a long time with no problems.
I have sheet2 two with links from sheet 1 and formulas. Mostly I do all the processing in sheet1 change event because I got circular refernces when putting functions in a cell.
From yesterday, I have a problem that the cell in sheet 2 shows 0. When I go to the linked cell it has data. Sometimes numbers and sometimes text depending, but sheet 2 shows 0.
As well as the linked cells, I also screen scrape some data with a seperate process and place it sheet 3 to link across to other cells, so sheet2 will also contain links form this data. I spent today changing this so it places the data in directly in sheet1 instead of creating links. This is tedious and will cause other problems.
I checked options -> formulas. Right now it is set at max iterations 100; max change 100. I had reduced max iterations to stop some functions firing themselves recursively through the sheet change event. Now I raised it back to 100.
I deleted all the data saved the sheet started again and the same thing happened again.
e.g. sheet1 cell "A1" has a value of 10
sheet2 cell a1 has a formula of ='sheet1'!A1
sheet 2 cell A1 is showing 0
when I look in the formula bar I see the formula
This data was damaged down to row 42 the last row that had held data. below that the conditional formatting was the correct color even though the formulas looked identical and i could see nothing wrong to explain it, I dragged the formula from 44 upwards again and everything worked, but bizarrely, when I copied from sheet1 cells 1 to 44 and pasted a link back in, I still got 0.
When I run the system and the COM erver delivers a load and the change event fires etc, I end up back with the same problem.
Now when I add a new sheet and paste my links from sheet1 into this, it works as it should.
Right now after my attempts to fix it. All sheet1 and sheet2 columns are formatted general though previousy I had one column text and some others number. I can't control the format of sheet1 because excel just adapts to the data it receives regardless what I do.
I also keep checkng for application.enableevents and this is not the problem nor is worksheet calculate and in the options I have automatic claculation set
The only other routine running under sheet change in sheet 2 is a tidyup that clears out old data after the COM server has delivered a smaller number of rows.
It copies default data from unused cells in the sheet. I placed the right formatting and default such as blank or 0 depending on what is required. This has not in the past caused any issues and I cant see what it might do, though previously when I just tried puttng "" in the cells to be cleared that did cause nasty excel erros. but not now.
Does anyone have any ideas?
I don't know if this is still relevant, but I had the same issue and came here searching for an answer.
In my case, I realized the cell I was trying to copy was a merged cell (i.e. it provided a range) the formula was [='Sheet1'!B10:N10] and the result was 0 and not the text I wanted. so I changed the formula to ='USA-CA'!B10 and it worked.
hope this is helpful to someone else.
This little routine fixes it.
Sub fixformulas()
'fix formulas broken by excel for some reason
Cells.Replace What:="=", Replacement:="=", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End Sub
All I can work out is that when excel copies the formulas and puts them back in place it corrupts the equals sign. Everything else is fine but as oon as I replace this the lights go on.
I'd rather know how to prevent it, but I hope nobody else suffers like I have.

VB code for VLOOKUP

I'm completely new to VBA. I tried recording a macro of using VLOOKUP function in my spreadsheet, but turns out VLOOKUP recorded like that does not work.
I have a working spreadsheet and I am comparing values in the column "Material" with a different workbook that is like a database for all the materials and their respective programs. The program the material number matches to in the database will be recorded under column "Program" in the working spreadsheet. I use VLOOKUP to do this, but I am having a hard time coming up with a macro for it.
As suggested, I did the following:
ActiveCell.FormulaR1C1 = "'Program"
Range("K41").Select
ActiveCell.Formula = "VLOOKUP(D41,"'C:\Users\Username\Desktop[Database.xlsx]Sheet1!R1C1:R152289C4,4,FALSE)"
But it still does not populate the "Program" column. What am I doing wrong?
The exact line for vlookups can be done in two ways;
1) This does a vlookup within the coding environment, it's more difficult to make it dynamic
application.worksheetfunction.vlookup(worksheets("Material").range("A2"), worksheets("Program").range("A1:F10"),4,0)
2) Make the formula in the cell the vlookup
range("c2").select
activecell.formula = "=vlookup(A1,Material!A1:F10,4,0)"
and then use the environment to fill in.
Maudise
Big thank you to all who took the time to address my question. I took suggestions, played around with the formula, and this is what I got:
=VLOOKUP($D41,'C:\Users\Username\Desktop[Database.xlsx]Sheet 1'!$A$1:$B$40973,2,FALSE)
Does exactly what I wanted it to do! Thanks again!

Need to Update External References in an Excel Sheet while a Macro is Running

I have an excel macro that sets Cells to an external location.
Range(NamedReference) = "='http://webaddress/ExcelSheet.xlsx'!NamedReference
Other cells use that location to calculate new values.
"A1" = NamedReference + 1
The problem is that I need to read the new calculated values back into the macro to export data, but the external link has not yet been calculated to any value. It is a #NAME? until the macro is done running. Is there any way to force excel to get those values during the macro run time?
I have tried a variety of things including
Calculate
CalculateFull
Any help would be appreciated. My current solution is to just close the macro on error and have the user re run the macro, but it is really kludgey.
**Edit: Forgot equals sign in formula
You could try
ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
See on MSDN