Can't get VLookup to work with another Excel file - excel

I am trying to place data from one excel file to another, using VBA's VLookup, but without success.
No error is shown and nothing happens. My cells are not being populated although after verification, they should. I cannot debug more than I have, as everything seems to be okay concerning the path, sheet name, and cell rows. I am trying to fetch a value from the source file (SourceFile.xlsx) after a key match on Column B (which contains a unique number).
I have tried the following code with and without the source file being opened, with exact same results:
If Application.WorksheetFunction.VLookup(.Range("B" & cell.Row), Workbooks("C:\Users\halpsb\Desktop\projet_macro\SourceFile.xlsx").Sheets("Projects_2015").Range("B" & cell.Row), 9, False) = "Yes" Then
.Range("D" & cell.Row) = Application.WorksheetFunction.VLookup(.Range("B" & cell.Row), Workbooks("C:\Users\halpsb\Desktop\projet_macro\SourceFile.xlsx").Sheets("Projects_2015").Range("B" & cell.Row), 7, False)
Else
.Range("D" & cell.Row) = ""
End If
Thank you in advance for any kind of help.
Edit: As precised in a comment below, the 7th column is used for my test and contains either "Yes" or "No" strings in the source file. Depending on this value, the 9th column of the source file is used for fetching data and placing it in my original file.

Your Vlookup formulas contain a "7" and a "9" as they are trying to retrieve data from the 7th and 9th column in the range specified by the second parameter.
BUT, you 2nd parameter only contains one column, which will cause an error
you could add error handlin similar to the example below
Sub aa()
On Error Resume Next
Debug.Print Application.WorksheetFunction.VLookup(2, Sheet1.Range("E4:E10"), 3, False)
if err.number <> 0 then
Debug.Print Err.Number, Err.Description
' an error occurred!
end if
End Sub
Consider this. The 2nd parameter is a single column! The 9 is trying to get the 9th column!
If Application.WorksheetFunction.VLookup(
.Range("B" & cell.Row)
, Workbooks("C:\Users\halpsb\Desktop\projet_macro\SourceFile.xlsx").Sheets("Projects_2015").Range("B" & cell.Row)
, 9
, False) = "Yes"

Related

How to Trim Headings in a table with VBA code

I'm trying to trim the headings of a table with VBA code because some of them have spaces in front that varies every month, which makes it difficult for coding.
When I break down the code and run it step by step it works fine but when I run the whole macro it removes some of my headings and replace them with info from a different sheet row or just "column 1", "column 2", etc.
I believe I'm missing some code reference when it calls the (" & .Address & ") selection?
It's replacing the headings from a sheet where the cell is active. (If it was the last cell to click on before running the macro).
I've tried just using the Trim function, but because it's an array for the range, it doesn't work, and someone suggested to use the "evaluate" function.
I've tried using the trim function as a WorksheetFunction as well but it gave me an error "Run-time error 13" Type-mismatch". Which was on the following code:
With wsDispoData.ListObjects("Table_DispoData").HeaderRowRange.EntireRow
.Value = WorksheetFunction.Trim(.Value)
End With
This is the current code I'm using that replaces wrongly.
Trim headings
With wsDispoData.ListObjects("Table_DispoData").HeaderRowRange.EntireRow
.Value = Evaluate("IF(ISTEXT(" & .Address & "),TRIM(" & .Address & "),REPT(" & .Address & ",1))")
End With
Expected results should be for example:
Current headings: " SOH" and " Compo"
Trimmed: "SOH" and "Compo"
I would just enumerate through the header row and check each value
Dim Cell As Range
For Each Cell In wsDispoData.ListObjects("Table_DispoData").HeaderRowRange
Cell.value = WorksheetFunction.Trim(Cell.value)
Next Cell

Excel VBA - Check cells in a column do not contain the string 8254 and display MsgBox

I am trying to put some vba code together to check if the contents in every cell from L2 down to the last row of data (until a blank cell is found) does not contain the string '8254' The number codes in column L are 27 characters long and always contain '8254' as the last 4 digits. So if I can verify '8254' in every cell then the format/code is correct (some number codes are incorrect and need to be investigated). If the string '8254' is not present in one or more of the cells, display a MsgBox warning there are error(s) in the column.
I have been trying to make the below code work, however I am new to vba and need some help
Does anyone know how I can do this?
Thanks
Sub CheckCodes()
'Check column 'L' for Non Standard Number Codes
Dim code As Range
For Each code In Range("L2", Range("L" & Rows.Count).End(xlUp))
If VBA.Right$(VBA.Trim$(code), 4) <> "8254" Then
MsgBox "Non Standard Number Codes Found! " & vbNewLine & "Check Number Codes ", , "ADVISORY!"
Exit Sub
End If
Next code
End Sub
I found the issue was that the code was checking a number of blank cells down to line L1000 and causing the issue. I modified as per below so it only checks to the bottom of the data and it is working fine. Thanks for all your kind help and comments.
Sub CheckCodes()
'Check column 'L' for Non Standard Number Codes
Dim code As Range
For Each code In Range("L2", Range("L" & Rows.Count).End(xlUp))
If VBA.Right$(VBA.Trim$(code), 4) <> "8254" Then
MsgBox "Non Standard Number Codes Found! " & vbNewLine & "Check Number Codes ", , "ADVISORY!"
Exit Sub
End If
Next code
End Sub
Using right function (assumes check is that 8234 are always last four digits):
Sub CheckCodes()
Dim code As Range
For Each code In Range("L2:L1000")
If VBA.Right$(VBA.Trim$(code), 4) <> "8234" Then
MsgBox "Non Standard Number Codes Found! " & vbNewLine & "Check Number Codes ", , "ADVISORY!"
Exit Sub
End If
Next code
End Sub

Run-time error '1004' - Method 'Range' of object'_Global' failed

I have a problem in VBA with a line throwing back an error.
What the macro is intended to do is find a particular cell then paste data into it.
The code is as following:
'To find Column of Customer imput
For Each cell In Range("B4:M4")
If cell.Value = strLeftMonth Then
DataImportColumn = cell.Column
End If
Next
For Each cell In Worksheets("data customer monthly 2013").Range("A3:A9999")
'First Customer
If cell.Value = strFirstCustomer Then
DataImportRow = cell.Row
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value = iFirstCustomerSales ****
End If
After running the above code; The code crashes giving the 1004 run-time error on the asterisk'd line. Also DataImportColumn has a value of 7 and DataImportRow has a value of 5.
Now my concern is that Columns aren't referenced as numbers but letters, so it must be that my code can never work because its a terrible reference.
Does anyone have any suggestions how I can make the above work?
Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.
http://www.bettersolutions.com/excel/EED883/YI416010881.htm
Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales
This should fix your problem.
Change
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value
to
Cells(DataImportRow,DataImportColumn).Value
When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)
Also one more tip. You might want to fully qualify your Cells object. for example
ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

VBA code for excel - delete rows that contain only capital letters, data is not like

Looking to determine the code to remove rows that contain all uppercase letters. The data I am preparing is contained in one worksheets from rows 1:900. The way the current data reads is ;
I WANT TO DELETE THIS LINE
I want to keep this line
243-4291 GASKET I want to keep this line
In this case, all that I have managed to do so far is remove rows with uppercase, however if you look at the 3rd line the work GASKET is upper case, I need to keep that line.
EDIT: Gary's suggestion, run backwards as to not skip iterations.
Is this what you're looking for?
Sub DelCaps()
For i = 900 to 1 Step -1
If Range("A" & i).Value = UCase(Range("A" & i).Value) Then
Range("A" & i).EntireRow.Delete
End If
Next i
End Sub
That's set for column A, if it's not obviously change it. Tested, I think it solves your problem if I understand you correctly.
EDIT: This will also delete rows with BLANK cells in the A column. If you don't wish to do so, the if statement changes to:
If Range("A" & i).Value = Ucase(Range("a" & i).Value) and Range("a" & i).Value <> "" Then

Colour an entire row based on the contents of one of its cells

I'm trying to color a spreadsheet based on the results given in one of it's columns. I'm using the following code:
With newSheet.Range("B:B")
.FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "CORRECT")
.FormatConditions(1).Interior.ColorIndex = 4
.FormatConditions.Add(Excel.XlFormatConditionType.xlCellValue, Excel.XlFormatConditionOperator.xlEqual, "INCORRECT")
.FormatConditions(2).Interior.ColorIndex = 3
End With
Unfortunately this only colors the cell containing "CORRECT" or "INCORRECT". I'd like it to extend to the row they are in (for example, if B12 contains "CORRECT", I want A12:G12 to all be coloured green). It was suggested that I try using an expression and so I tried the following code:
.FormatConditions.Add(Type:=XlFormatConditionType.xlExpression, Formula1:="=B" & row & "= ""CORRECT"")")
.FormatConditions(1).Interior.ColorIndex = 4
This however, returns an E_INVALIDARG exception. I'd appreciate any tips on how to go about fixing this. I should also note that looping through every row and checking one at a time is not really an option, as there are many thousands of lines.
Your formula should work once you remove your excess closing parenthesis and make the column an absolute value
.FormatConditions.Add(Type:=XlFormatConditionType.xlExpression, Formula1:="=$B1= ""CORRECT""")
.FormatConditions(1).Interior.ColorIndex = 4
Make sure you set the row in your formula $B1 as the first row of your formatted range (you don't need to do a loop)
You can paste this into the sheet(s) in question:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Integer
i = 1
While Range("B" & i).Value2 <> ""
If Range("B" & i).Value2 = "INCORRECT" Then
Range("A" & i & ":G" & i).Interior.ColorIndex = 3
ElseIf Range("B" & i).Value2 = "CORRECT" Then
Range("A" & i & ":G" & i).Interior.ColorIndex = 4
Else
Range("A" & i & ":G" & i).Interior.ColorIndex = 0
End If
i = i + 1
Wend
End Sub
This assumes your data starts in row 1 (otherwise change the starting value of i).
This is a very, very low-tech answer. But after you've got the cells highlighted in the color you need them to be (using the code), copy all the values in the column and do a paste-special for "Formats" on the rows themselves.
Problem with that is that it'll be static, and if your values change with inputs, the coloring on the rows will be off.
But if it's a one-time thing, that may work.
If you do this, make sure that the column you're evaluating has a cell format type (ie: "General", "Text", etc) that's compatible with the data in the rows you're pasting onto.
Kludgey, but if you absolutely need this fast and you only need to do it once, it might work.
Edit: Pretty sure Kevin's answer below is a better one, as it actually solves it with code and seems like it'd work even if the values change in the evaluated cells.

Resources