VBA - copy rows - if it found error, then continue in copy cells - vba

I have macro which copy cells to below's cells.
Sub CopyRows2()
Dim LastRow As Long
With Worksheets("Ready to upload") ' <-- here should be the Sheet's name
LastRow = .Cells(.Rows.Count, "AD").End(xlUp).Row ' last row in column C
For i = 2 To LastRow
If Range("AD" & i) > "" And Range("AD" & i + 1) = "" Then
Range("AD" & i).Copy
Range("AD" & i + 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Else
End If
Next
End With
ActiveWindow.ScrollRow = 1 'scrolling the screen to the top
End Sub
It works fine, until it will found #N/A, then it will give me an error msg: Run-time error '13' - type mismatch. In that case, I would like to skip it and then continue in copy rows.
[
Could you advise me, how to do that, please?
Many thanks!

Option 1
The easiest way is to embed On Error Resume Next in your code. Then it will work.
Option 2
If you want to be one step more professional, then you can use something like this:
Sub CopyRows2()
Dim LastRow As Long
On Error Resume Next
'your code
If Err.Number = 13 Then Err.Clear
On Error GoTo 0
End Sub
It will disregard error 13, but it will tell you if there are other errors, which is quite useful.
Option 3 Check for error like this:
If Not IsError(Range("AD" & i)) And Not IsError(Range("AD" & i + 1)) Then
'embed the code here
End If

Related

Copy - paste values while creating growing List

I want to have a macro which runs everytime I open the excel-file, then compares the date (I5) with the last entry in a list (column L), and if the date is older, copy some values (I5 and I11) and paste them in the next empty row of the list (columns L and M). I have written the code bellow but it does not work, I get runtime error 424 and every other syntax I found online and tried to adapt isn't working either. Can anyone help ?
Private Sub Workbook_Open()
If Worksheets("overdue").Range("I5").Value > Worksheets("overdue").Range("L2").End(xlDown).Value Then
Worksheets("overdue").Range("I5").Copy
Worksheets("overdue").Range("L1").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
Worksheets("overdue").Range("I11").Copy
Worksheets("overdue").Range("M1").End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
End If
End Sub
Try the code below, in case you have only 1 row in column "L" (I guess header):
Private Sub Workbook_Open()
Dim LastRow As Long
With Worksheets("overdue")
LastRow = .Range("L1").End(xlDown).Row
If LastRow >= 2 Then
If .Range("I5").Value > .Range("L" & LastRow).Value Then
.Range("L" & LastRow + 1).Value = .Range("I5").Value
.Range("M" & LastRow + 1).Value = .Range("I11").Value
End If
End If
End With
End Sub

On Error Goto Line1 not working in VBA

I am working on a VBA code to identify changes in data in two different excel sheets. The code matches the data in first columns (A2 then A3 and then A4....) and checks the row for data in the other sheet. However when the code gets interrupted when it is unable to find data that is in the first sheet but not in the second sheet. The find function returns nothing.
I need your help on this as I am unable to get On Error Goto Line1 statement working.
Best,
Nishant
VBA Code for the same:
Sub Compare()
Var = 2
Sheets("Sheet1").Select
Do Until Range("A" & Var).Value = ""
Sheets("Sheet1").Select
var1 = Range("A" & Var).Value
Sheets("Sheet2").Select
Range("A1").Select
On Error GoTo Line1
var2 = Range("A:A").Find(What:=var1).Row
For i = 1 To 6
If Worksheets("Sheet1").Cells(Var, i).Value <> _
Worksheets("Sheet2").Cells(var2, i) Then
Worksheets("Sheet2").Cells(var2, i).Interior.ColorIndex = 3
End If
Next
Line1:
Var = Var + 1
Loop
End Sub
You are not using error-handling correctly. For instance, after hitting an error you are attempting to continue processing as if nothing has occurred. That will cause an untrappable error when the next error occurs.
It is much better to avoid error handling unless absolutely necessary, and in this case it isn't necessary.
Sub Compare()
Dim FindRange As Range
Dim Var As Long
Dim Var2 As Long
Var = 2
Do Until Worksheets("Sheet1").Range("A" & Var).Value = ""
var1 = Worksheets("Sheet1").Range("A" & Var).Value
Set FindRange = Worksheets("Sheet2").Range("A:A").Find(What:=var1)
If Not FindRange Is Nothing Then
var2 = FindRange.Row
For i = 1 To 6
If Worksheets("Sheet1").Cells(Var, i).Value <> _
Worksheets("Sheet2").Cells(var2, i) Then
Worksheets("Sheet2").Cells(var2, i).Interior.ColorIndex = 3
End If
Next
End If
Var = Var + 1
Loop
End Sub

Run time error 1004 on using Vlookup function

Im trying to highlight range of cells when a date is present in the list of holidays. But on running the below code, the Run time error 1004 is displayed. I have even tried handling it in error handler; but it is not working. Can somebody please help me why this error is occuring and resolve the same?
Sub highlight_cells()
Dim myrange As Range
On Error GoTo myerr:
For i = 1 To 10
Set myrange = Range(Cells(1, i), Cells(10, i))
temp = Application.WorksheetFunction.VLookup(Range(Cells(1, i)), [holidays], 2, False)
If (Application.WorksheetFunction.IsNA(temp)) Then
myrange.Interior.Color = 3
End If
Next i
myerr:
If Err.Number = 1004 Then
MsgBox "vlookup error"
End If
End Sub
Range(Cells(1, i)) isn't a valid range reference
maybe you wanted to reference Cells(1, i)
furthermore you can exploit the Application VLookup() method that wraps the possible error in the returned variant variable that you can check with IsError() function like follows:
Dim temp As Variant
For i = 1 To 10
Set myrange = Range(Cells(1, i), Cells(10, i))
temp = Application.VLookup(Cells(1, i), [holidays], 2, False)
If Not IsError(temp) Then Cells(1, i).Interior.Color = 3
Next i
Here is a conditional formatting method, without using VBA.
Select your range > Conditional Formating > New Rule > Use a formula ...
Enter this formula
=VLOOKUP($A2,$J$2:$K$6,1,FALSE)
Take care of the "$" in the formula. This should highlight all cells that were found in the holidays list.
Your code is okay , It worked in Excel 2010 , Your problem is with VBA Error handling method.
Go to Tools --> Options -->General --> Error Trapping
And check "Break on unhanded Errors"
sorry all these times I was referring to column 2 in vlookup. That was causing the problem. The list of holiday is a single column list. Hence vlookup was throwing error. ANd one more thing the named ranges work as I have entered and even the actual range also gives the same result.
Sub highlight_cells()
Dim myrange As Range
For i = 1 To 10
Set myrange = Range(Cells(1, i), Cells(10, i))
MsgBox Cells(1, i)
temp = Application.VLookup(Cells(1, i), [holidays], 1, False)
If Not IsError(temp) Then
myrange.Interior.ColorIndex = 3
End If
Next i
End Sub

'Exit For' is not working

Doing a reverse for loop in Excel VBA, looking for the last populated cell in a certain column. Once found, it should exit the loop, but Exit For is not working, and continues looping all the way back. Any ideas?
rewind:
' so we 're still "under", rollback to the right line
While Not Range("I" & a).Value = getsum
a = a - 1
On Error GoTo TryCatch
If Not Range("E" & a).Value = "" Then
Rows(a).Select
currfield = Range("E" & a).Value
runningstrsum = runningstrsum - currentstrsum 'we're switching streets
' and since we just lost currentstrsum, we have to reset it to the last one, yay
For c = a - 1 To 2 Step -1
If Not Range("E" & c).Value = "" Then 'there it is
currentstrsum = Range("E" & c).Value
Exit For
End If
Next c
End If
Wend
If overunder < 0 Then 'go back to overunder<
GoTo goodjobunder
ElseIf overunder = 0 Then
GoTo goodjobeven
End If
You're only exiting the inner loop, the code will resume outside of this loop - which is still inside the While loop and therefore re-enter the For loop.
If you want to find the last populated cell in a column just use something like:
Dim lastCell As Excel.Range
Set lastCell = Range("E" & Rows.Count).End(xlUp)
No need to loop.
Might also be a good time to look at Debugging VBA Code

Vlookup Dates in Excel VBA

I am working with 3 excel sheets. In sheet Start Page i have Dates starting from column A4 going down. The macro Vlooks up in sheet Fund Trend for the same Dates which are locate in column A11 to lastrow and offsets 3 columns , and copies the Value into sheet "Accrued Expenses" starting from Range("C7"). Macro loops until the lastrow in sheets("Start page") Range("A4") .
The Problem is that the macro is not populating the values into sheet Accrued expenses, on some occasions. OR its not finding the Date. My code is below:
Sub NetAsset_Value()
Dim result As Double
Dim Nav_Date As Worksheet
Dim fund_Trend As Worksheet
Dim lRow As Long
Dim i As Long
Set Nav_Date = Sheets("Start page")
Set fund_Trend = Sheets("Fund Trend")
lRow = Sheets("Start page").Cells(Rows.Count, 1).End(xlUp).row
For i = 4 To lRow
result = Application.WorksheetFunction.VLookup(Nav_Date.Range("A" & i), fund_Trend.Range("A11:C1544"), 3, False)
Sheets("Accrued Expenses").Range("C" & i + 3).Value = result
Sheets("Accrued Expenses").Range("C" & i + 3).NumberFormat = "0.00"
Sheets("Accrued Expenses").Range("C" & i + 3).Style = "Comma"
Next i
End Sub
Error Trap:
On Error Resume Next
result = Application.WorksheetFunction.VLookup(Nav_Date.Range("A" & i), fund_Trend.Range("A11:C1544"), 3, False)
If Err.Number = 0 Then
Sheets("Accrued Expenses").Range("C" & i + 3).Value = result
Sheets("Accrued Expenses").Range("C" & i + 3).NumberFormat = "0.00"
Sheets("Accrued Expenses").Range("C" & i + 3).Style = "Comma"
End If
On Error GoTo 0
To over come the Date issue i have this sub dont know if this is efficient?
Sub dates()
Sheets("Start page").Range("A4", "A50000").NumberFormat = "dd-mm-yyyy"
Sheets("Fund Trend").Range("A11", "A50000").NumberFormat = "dd-mm-yyyy"
End Sub
The issue that i am now having is that when enter a date like 11/02/2015 it switches to 02/11/2015. But its not happening to all Dates
Overcoming the Problem. I am placed a worksheet function to force the date columns to text. Which is currently working.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Sheets("Start page").Range("A4", "A50000").NumberFormat = "#"
Sheets("Fund Trend").Range("A11", "A50000").NumberFormat = "#"
End Sub
To avoid the 1004 error you can use the Application.VLookup function, which allows an error type as a return value. Use this method to test for an error, and if no error, return the result.
To do this, you'll have to Dim result as Variant since (in this example) I put a text/string value in the result to help identify the error occurrences.
If IsError(Application.Vlookup(Nav_Date.Range("A" & i), fund_Trend.Range("A11:C1544"), 3, False)) Then
result = "date not found!"
Else
result = Application.WorksheetFunction.VLookup(Nav_Date.Range("A" & i), fund_Trend.Range("A11:C1544"), 3, False)
End If
The "no result printed in the worksheet" needs further debugging on your end. Have you stepped through the code to ensure that the result is what you expect it to be, for any given lookup value? If there is no error, then what is almost certainly happening is that the formula you have entered is returning a null string and that value is being put in the cell.