VLookup a value in workbook with code in another workbook - excel

I have two workbooks: one with the macro and one with data. I am trying to look up a value in the workbook with data. After the code with VLookup is reached it stops, and everything after isn't executed.
I checked all things I can think of. I checked if some random cell from data workbook can be reached: MsgBox (budgetWorkbook.Sheets("sheet 1").Range("E16").Value), it works fine.
I checked if my search value equals with the corresponding value in column A of data workbook, it works - it msgboxes "Equals".
Dim i As Integer
Dim budgetItemSheetName As String
i = 1
Dim budgetItemValue As Long
MsgBox (budgetWorkbook.Sheets("sheet 1").Range("E16").Value) 'shows up
If budgetItemNames(i) = budgetWorkbook.Sheets("sheet1".Range("A16").Value) Then
MsgBox("Equals") 'shows up
End If
budgetItemValue = Application.VLookup(budgetItemNames(i), _
budgetWorkbook.Sheets("sheet 1").Range("A:B"), _
2, False) 'fails, but it should find the search value in A16 cell and give B16 cell's value
resultArray(i) = budgetItemValue 'doesn't work
MsgBox (budgetItemValue) 'doesn't show up
EDIT: Looks like I will have to use a custom search function.

Just made a small test with a small lookup table, Column A and Column B and the lookup value in Cell D1:
Public Sub TestVLookup()
Dim wb As Workbook
Dim rng As Range
Set wb = Application.ThisWorkbook
Set sht = Application.Sheets("Tabelle1")
budgetItemValue = Application.VLookup(Cells.Range("D1"), sht.Range("A1:B5"), 2, False)
Debug.Print "The Result is " & budgetItemValue
End Sub

Related

Can not SUM selected cells With SUMIF

I would like to be able to Check for criteria "owners" In column A and SUM cell from the same row column E with the cell above and repeat through the spread sheet where owner is found.
I have tried to use Function =SUMIF(A3,"*owner*",E2:E3) This returns the Value above the cell in the row with owner but does not SUM them.
I have also tried this VBA CODE and it does the same thing.
Sub vba_sumif()
Dim gRange As Range
Dim sRange As Range
Set gRange = Range("A3")
Set sRange = Range("E2:E3")
Range("G2") = _
WorksheetFunction.SumIf(gRange,"*Owner*", sRange)
End Sub
Ideally it would return the summed cells in the above cell. using VBA
Thanks again,
Aaron
Well first of all, I would suggest just using the formula unless you have a reason not to:
Formula:: Your first error with the formula is both ranges need to be the same size.
VBA:: Same thing here with range sizes, then you also need to remember to make sure Excel knows what sheet you're referring to. I like to do this with a With My_Worksheet_Namestatement, then include a . before any range from that sheet. Just make sure to change the sheet name to your sheet name
Option Explicit
Sub vba_sumif()
Dim TableSheet As Worksheet
Dim gRange As Range
Dim sRange As Range
Set TableSheet = Worksheets("TableSheet")
With TableSheet
Set gRange = .Range("A2:A13")
Set sRange = .Range("E2:E13")
.Range("G2").Value = _
WorksheetFunction.SumIf(gRange, "*Owner*", sRange)
End With
End Sub

Why isn't this Vlookup loop macro working?

I am trying to write an Excel macro that will perform a VLOOKUP on cells 9:100 of column K on 1155 individual sheets (named Page 1, Page 2, etc) of a workbook. I want to run the macro in another workbook, though. So I'm trying to target the cells in one workbook to populate cell values in another.
I have this. However, when I run it, all it does is replace the contents of the specified cells on the first sheet with "#VALUE!". It doesn't do anything to the other sheets.
Sub SearchPages()
Dim i As Integer
Dim cell As Range
Dim value As Variant
Dim result As Variant
Dim wb As Workbook
Set wb = Workbooks.Open("file.xls")
For Each cell In Range("K9:K100")
value = cell.value
result = "Not Found"
For i = 1 To 1155
On Error Resume Next
result = Application.VLookup(value, "Page " & i & "!K:N", 4, False)
On Error GoTo 0
If Not IsError(result) Then
Exit For
End If
Next i
cell.value = result
Next cell
End Sub
Is what I'm trying to do even possible? Any insight is much appreciated!

How to compare cells one by one between two Excel sheets?

I'm trying to write a VBA code and I'm having some issues.
Here's the context, I have an Excel spreadsheet with two sheets, "Sheet1" and "Sheet2"
I want my VBA code to compare two rows of cells.
Here's what my Sheet1 looks like:
And here's what my Sheet2 looks like:
As you can see, I have the same number of cells to compare however, one of them is not the same.
What I want my VBA code to do, is to compare one by one the cells between Sheet1 and Sheet2. And once the code spots two cells who are not identical, a MsgBox appears saying "Cells are not the same". In that case, it is for cells "D1"
It sounds pretty basic and simple to do, but I'm really struggling.
Here are the first lines of code I have but it doesn't work:
Dim RangeSheet1 As Range, RangeSheet2 As Range
Set RangeSheet1 = Worksheets("Sheet1").Range("A1")
Set RangeSheet2 = Worksheets("Sheet2").Range("A1")
Do While RangeSheet1.Value = RangeSheet2.Value
RangeSheet1.Offset(0,1)
RangeSheet2.Offset(0,1)
Loop
MsgBox "Cells are not the same"
Do you guys have any idea how I can do it the right way?
Thank you very much for your help.
I wrote a solution that compares all the cells in the sheets using a for loop. It exits the for loop when two cells are not equal, but if you need to compare more cells you can just remove that row. There are more efficient macros but this is a solution that I think should work for your needs.
Sub compareSheets()
Dim sht1 As Worksheet, sht2 As Worksheet, cell As Object
Set sht1 = Worksheets("Sheet1")
Set sht2 = Worksheets("Sheet2")
For Each cell In sht1.Cells
Dim currentCellAddress As String
currentCellAddress = Replace(cell.Address, "$", "")
If Not cell.Value = sht2.Range(currentCellAddress).value Then
MsgBox "The cell " & currentCellAddress & " is not the same in both sheets."
Exit For
End If
Next cell
End Sub
EDIT:
I saw you to collect all the non-equal cells in a message box at the end. Then in that case, something like this should do the trick:
Sub compareSheets()
Dim sht1 As Worksheet, sht2 As Worksheet, cell As Object, refArray() As String, refCount As Integer
refCount = 0
Set sht1 = Worksheets("Sheet1")
Set sht2 = Worksheets("Sheet2")
For Each cell In sht1.Cells
Dim currentCellAddress As String
currentCellAddress = Replace(cell.Address, "$", "")
If Not cell.Value = sht2.Range(currentCellAddress).Value Then
ReDim Preserve refArray(0 To refCount)
refArray(refCount) = currentCellAddress
refCount = refCount + 1
End If
Next cell
Dim resultText As String, ref As Variant
For Each ref In refArray
resultText = resultText & " " & ref
Next ref
MsgBox "The following cells are not equal " & vbCrLf & resultText
End Sub

How to use Countifs formula in VBA?

I am working on a workbook where there are 8 worksheets.
Names of worksheets:
[Hierarchy, wins, outlook, pcv, misses, losses, backdate, login].
In "Hierarchy" worksheet I want to apply the formula in a column B, up to the last value of that column B (which includes names of sales person). (I guess we will use a loop, I'm not sure which loop should I use.)
=COUNTIFS(wins!$AL:$AL,Hierarchy!$B4,wins!$P:$P,"Complete")
PS: I need help in above countif formula and loop (in VBA) to use that formula up to the last record in the column.
If you just need a result as opposed to filling formulas down the column in a worksheet, you could use one of these options:
Fast one - only using loops:
Sub countifs_in_vba()
Dim Result As Long
Dim i As Long
Dim cell As Range
Dim wsHierarchy As Worksheet
Dim wsWins As Worksheet
Set wsHierarchy = ThisWorkbook.Sheets("Hierarchy")
Set wsWins = ThisWorkbook.Sheets("wins")
For Each cell In Intersect(wsHierarchy.Range("B:B"), wsHierarchy.UsedRange)
For i = 1 To wsWins.Cells.SpecialCells(xlCellTypeLastCell).Row
If cell.Value = wsWins.Cells(i, "AL").Value And wsWins.Cells(i, "P").Value = "Complete" Then
Result = Result + 1
End If
Next
Next
MsgBox Result
End Sub
Slower one - employing Application.WorksheetFunction:
Sub countifs_in_vba2()
Dim Result As Long
Dim cell As Range
Dim wsHierarchy As Worksheet
Dim wsWins As Worksheet
Set wsHierarchy = ThisWorkbook.Sheets("Hierarchy")
Set wsWins = ThisWorkbook.Sheets("wins")
For Each cell In Intersect(wsHierarchy.Range("B:B"), wsHierarchy.UsedRange)
Result = Result + Application.WorksheetFunction.CountIfs(wsWins.Range("AL:AL"), cell.Value, wsWins.Range("P:P"), "Complete")
Next
MsgBox Result
End Sub

Using excel formula to copy a column between workbooks if first cell contains any info

I'm tyring to look for a way to return a range of cells with just the lookup function. Is this really possible?
Basically like this:
=LOOKUP([MasterBook.xlsm]Sheet3!$A:$A,?)
I just want the function to look in the main workbook through all of Column A and return all cells for Column A that have something in them.
EDIT for poster below:
Sure. I have two workbooks; one workbook is essentially a local product that has a "master" sheet on top and then individual worksheets following it that have all of their information extracted from the master sheet. The second workbook is a local copy of a product that I send to a non-local entity higher up the food chain. Basically I need to pull information from the individual sheets in my first workbook and put it in the appropriate columns in the second workbook. I have a macro that gets the info from my sheets in the one workbook over to the other, but the second workbook is formatted differently. I was looking for a way to use a formula if possible.
The macro I am referring to is:
Sub CopyTest()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn = Workbooks("Local Workbook.xlsm").Worksheets("Sheet3").Columns("A")
Set targetColumn = Workbooks("Nonlocal Workbook.xlsm").Worksheets("Sheet1").Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
All this does is pull the specified column from one sheet and put it in the column on the second book; but it just pastes it starting in the first block. Since the non-local book is formatted differently, the column I need to transfer to doesn't start until Row 9. shrug I have ideas abuot what I'm trying to do with this, but my ideas tend to exceed my technical ability (which occasionally makes it difficult to explain). :)
Depending on how different your workbooks are formatted. Here is two way to handle this:
Adapt your macro
Instead of copying the whole column, you can copy paste, only the values you want to.
Here is an example:
Sub CopyTest()
Dim rSource As Range, rTarget As Range
Dim lEnd As Long
lEnd = Range("A65536").End(xlUp).Row
Set rSource = Workbooks("Local Workbook.xlsm").Worksheets("Sheet3").Range("A1:A" & lEnd)
Set rTarget = Workbooks("Nonlocal Workbook.xlsm").Worksheets("Sheet1").Range("A9")
rSource.Copy Destination:=rTarget
End Sub
Use a formula
If your data are not in the same order, you'd better use a VLOOKUP formula.
See how it works.
Don't hesitate to post another question with what you've built for some help. Please give as much details as possible so we could help you the best way.
[EDIT] Another try following the comments
Option Explicit
Dim wTarget As Workbook
Sub mainCopy()
Dim bGo As Boolean
bGo = True
'Add a new workbook to copy the data - do you want the user to select one?
Set wTarget = Application.Workbooks.Add()
Do While bGo
CopyTest
bGo = MsgBox("Do you want to import data from another workbook?", vbYesNo, "Continue?")
Loop
End Sub
Sub CopyTest()
Dim rSource As Range, rTarget As Range
Dim lEnd As Long, lCol As Long
Dim ws As Worksheet
Dim vFile As Variant
vFile = Application.GetOpenFilename("Excel-files,*.xls", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
For Each ws In ActiveWorkbook.Worksheets
'do you need to copy the columns separately?
' For lCol = 1 To 10
'find the last cell of the 10th column
lEnd = ws.Cells(65536, 10).End(xlUp).Row
Set rSource = ws.Range("A1:J" & lEnd)
'How can we define the target worksheet?
Set rTarget = wTarget.Worksheets("Sheet1").Range("A9")
rSource.Copy Destination:=rTarget
' Next lCol
Next ws
End Sub

Resources