On Error Goto Line1 not working in VBA - 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

Related

Excel VBA Macro to concatinate two columns using column header id name

I am really new in writing Excel macros through VBA. I want to concatenate two columns in my Excel worksheet. I have data in columns A, B & C and I want to concatenate B & C column to D column. This is the code I wrote:
Sub FINAL()
'
' FINAL Macro
'
'
Columns("D:D").Select
Selection.Insert Shift:=xlToRight
Range("D2").Select
ActiveCell.FormulaR1C1 = "SO::LI"
Range("D3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=RC[-2]&""::""&RC[-1]"
Range("D3").Select
Dim lastRow As Long
lastRow = Range("C" & Rows.Count).End(xlUp).Row
Range("D3").AutoFill Destination:=Range("D3:D" & lastRow)
End Sub
This works fine. But This works only when my data is in columns A, B & C.
When the data is in different columns, such as E, F & G, this does not work.
So what I want is to find the column using column header name and concatenate data.
Style S/O L/I
392389 265146 40
558570 300285 10
558570 300285 20
After concatenation:
Style S/O L/I SO::LI
392389 265146 40 265146::40
558570 300285 10 300285::10
558570 300285 20 300285::20
You can find a column header by using the worksheet MATCH function inside VBA, here I'll put it in to a variable called c1
c1 = Application.WorksheetFunction.Match("S/O", Range("1:1"), 0)
It's best to wrap this identification in a potential error handler, because if there IS no match then you'll get a run-time error
If Application.WorksheetFunction.CountIf(Range("1:1"), "S/O") > 0 Then
c1 = Application.WorksheetFunction.Match("S/O", Range("1:1"), 0)
Else
MsgBox ("Couldn't find ""S/O"" header!")
Exit Sub
End If
Here it uses the worksheet function COUNTIF to make sure there is at least one instance of "S/O" - if there isn't then the subroutine ends.
After that, you've identified your S/O column so can carry on with the rest of the code as usual - if you assume the columns are always consecutive then you can use c1 + 1 to mean "L/I" column and c1 + 2 to mean the CONCAT column
Below is a fully working version of the code:
Private Sub CommandButton1_Click()
Dim c1 As Long
Dim lastRow As Long
' If instance of "S/O" exists then find the column number else show error message and end
If Application.WorksheetFunction.CountIf(Range("1:1"), "S/O") > 0 Then
c1 = Application.WorksheetFunction.Match("S/O", Range("1:1"), 0)
Else
MsgBox ("Couldn't find ""S/O"" header!")
Exit Sub
End If
' Get last row for formula based on the "S/O" column header in c1
lastRow = Cells(Rows.Count, c1).End(xlUp).Row
' add 2 to c1 to make the c1 variable contain column number for SO::LI
c1 = c1 + 2
' use FormulaR1C1 as usual to flood the whole column from row 2 to lastRow
Range(Cells(2, c1).Address, Cells(lastRow, c1).Address).FormulaR1C1 = "=RC[-2]&""::""&RC[-1]"
End Sub
You may give this a try...
The code will find the headers in row2 and concatenate the columns.
Sub Final()
Dim FirstCell As Range, SecondCell As Range
Dim lr As Long, r As Long, c As Long
Application.ScreenUpdating = False
'Assuming that the Row2 is the Header Row, if not change it.
Set FirstCell = Rows(2).Find("S/O")
If FirstCell Is Nothing Then
MsgBox "A column with the header S/O was not found.", vbExclamation
Exit Sub
End If
Set SecondCell = Rows(2).Find("L/I")
If SecondCell Is Nothing Then
MsgBox "A column with the header L/I was not found.", vbExclamation
Exit Sub
End If
r = FirstCell.Row + 1
c = SecondCell.Column + 1
Set FirstCell = FirstCell.Offset(1)
Set SecondCell = SecondCell.Offset(1)
lr = Cells(Rows.Count, SecondCell.Column).End(xlUp).Row
Columns(c).Insert
Range(Cells(r, c), Cells(lr, c)).Formula = "=" & FirstCell.Address(0, 0) & "&""::""&" & SecondCell.Address(0, 0) & ""
Application.ScreenUpdating = True
End Sub
Use FormulaR1C1 instead is useful
Sub mergeColumn()
Dim col As Integer
Dim tr As Long
Application.ScreenUpdating = False
On Error Resume Next
col = Rows(1).Find(What:="S/O").Column
On Error GoTo 0
If col <> 0 Then ' if not found, it goes to 0
tr = Cells(Rows.Count, col).End(xlUp).Row
Range(Cells(1, col + 2), Cells(tr, col + 2)).Value = "=RC[-2] & ""::"" & RC[-1]"
End If
Application.ScreenUpdating = True
End Sub

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

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

Excel VBA If then statements

i want to if my cell (b5,c5) is blank than cell (f5,g5,h5) also make blank also ,cell (b6,c6) is blank than cell (f6,g6,h6) ,cell (b7,c7) is blank than cell (f7,g7,h7) ,cell (b8,c8) is blank than cell (f8,g8,h8) ,cell (b9,c9) is blank than cell (f9,g9,h9) , but same in i want this code 200 time help me make a small code.thanks in advance.
Sub BLANK()
If Range("B5,C5") = "" Then
Range("F5,G5,H5") = ""
If Range("B6,C6") = "" Then
Range("F6,G6,H6") = ""
If Range("B7,C7") = "" Then
Range("F7,G7,H7") = ""
' same code in cell("b5:b200") make small code please
end if
end sub
I will recomend you to use something like this. Where ranges and sheet is properly declared, and also all variables are properly declared with using option explicit to prevent you from multiple issues
Sub makeBlank()
Dim mySheet As Worksheet
Set mySheet = Sheets("devSheet")
Dim rowCounter As Long
With mySheet
For rowCounter = 5 To 200
If .Range("B" & rowCounter & ",C" & rowCounter).Value = "" Then
.Range("F" & rowCounter & ",G" & rowCounter & ",H" & rowCounter).Value = ""
End If
Next rowCounter
End With
End Sub
The below will loop over 200 times and produce the results you require
For x = 5 to 200
If Range(Cells(x,2), Cells(x,3)).Value = "" Then
Range(Cells(x,6), Cells(x,8)).Value = ""
End if
Next x

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.

Logical error comparing two ranges cells values

This program aims to compare two named ranges in two sheets. If the cells values are found in both sheets it highlights cells in green otherwise in red.
In my code below, I get a logical error.
I compare the results in the two sheets manually but I get totally different results.
Public Sub FindBtn_Click()
range1Name = namedRange1TxtBox
range2Name = namedRange2TxtBox
sheet1Name = Sheet1txt
sheet2Name = Sheet2txt
Dim range1No(), range2No() As Variant
range1No() = Range(range1Name)
range2No() = Range(range2Name)
Dim i, j As Integer
Dim cell As Variant 'Range
For i = LBound(range1No()) To UBound(range1No())
For j = LBound(range2No()) To UBound(range2No())
Set cell = Worksheets(sheet1Name).Range(range1Name).Find(what:=Worksheets(sheet2Name).Range(range2Name).Cells(i, 1).Value, lookat:=xlWhole)
If Not cell Is Nothing Then ' if jde cell value is found in tops then green jde cell
Worksheets(sheet1Name).Range(range1Name).Cells(i, 1).Interior.ColorIndex = 4
Else
Worksheets(sheet1Name).Range(range1Name).Cells(i, 1).Interior.ColorIndex = 3
End If
Application.StatusBar = "Progress: " & i & " of " & UBound(range1No()) '& Format(i / 9331, "%")
Next j
Next i
Without spending a while on in, I'm not too sure what's actually wrong with your code. But how about doing it this way (I substituted strings in the variables so I could make it work locally).
Public Sub FindBtn_Click()
range1Name = "firstrange"
range2Name = "secondrange"
sheet1Name = "Sheet1"
sheet2Name = "Sheet2"
Dim range1cell As Range
Dim range2cell As Range
For Each range1cell In Range(range1Name)
range1cell.Interior.ColorIndex = 3
For Each range2cell In Range(range2Name)
If range1cell.Value = range2cell.Value Then
range1cell.Interior.ColorIndex = 4
Exit For
End If
Next range2cell
Next range1cell
End Sub
On looking closer, I notice that while you're looping through values of j you don't seem to refer to j anywhere else.
the following code solved my problem basicly I don't know how to use the find function properly. below a code that does the job :)
Thanks :)
Dim cell1 As Range, cell2 As Range
Dim add1 As Variant
With Worksheets("JDE").Range("JS_No")
For Each cell2 In Worksheets("TOPS").Range("TechID")
Set cell1 = .Find(cell2, LookIn:=xlValues)
If Not cell1 Is Nothing Then
add1 = cell1.Address
Do
cell1.Interior.ColorIndex = 4
cell2.Interior.ColorIndex = 4
Application.StatusBar = "Processing: " & add1
Loop While Not cell1 Is Nothing And cell1.Address <> add1
End If
Next cell2
End With