Why isn't this Vlookup loop macro working? - excel

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!

Related

Sum the equivalent cells across mulltiple workbooks while looping through cells then sheets in master

I have a template file, whereby multiple copies of the template (5 to 20) are completed, then consolidated into one master file. This file contains multiple sheets (18) and hundreds of entries in each sheet.
Not every cell is a number requiring consolidation, i.e there are titles and dates etc which are repeated, with no clear structure. Re-organising the template is not an option. The best way is to calculate only cells with a "Currency" type.
Here is the code I have so far. I have pieced it together from a number of searches, but will admit that I don't fully understand vba so I know I'm missing something obvious.
To make this a bit simpler, I have closed everything else and opened the target files manually before running this, then called upon the open excel files. Improving this bit of the code so that I can just put the target files into a sub folder and then use that path would be nice but not necessary.
I do not need to change the cell colour at the end, but I just did that as a quick visual reference to see whether it had ran.
The script in this format does not throw up any errors, but simply runs without actually calculating and populating the total value into each cell. I would guess that my approach of trying to extract the sheet and cell reference for every loop is wrong, but I cannot find the answer anywhere, so any help would be greatly appreciated.
totalValue = totalValue + Worksheets(sht).Cells(R, C)
is completely the wrong syntax, and the crux of the issue, but I simply don't know how to fix this within the context of the two existing For Each loops.
Sub ConsolidatedFigures()
Application.ScreenUpdating = False
'Declare variable types
Dim ws As Worksheet
Dim totalValue As Double
Dim C As Integer
Dim R As Integer
Dim wb As Workbook
Dim sht As String
Dim myRange As Range
Dim cell As Range
'Start to loop through each sheet in the workbook
For Each ws In ThisWorkbook.Worksheets
'get the current sheet name to later search for the same sheet in other workbooks
sht = ws.Name
'set the range in the current sheet
Set myRange = ws.UsedRange
'Now loop though every cell in the range
For Each cell In myRange
'Only target cells with an "currency" style so we're not trying to sum text
If cell.Style = "Currency" Then
'get the current cell references to later search for the same cell in other workbooks
C = cell.Column
R = cell.Row
'Within the current cell, go through open workbooks (except this one) to create a total of all the corresponding cells
For Each wb In Application.Workbooks
'the target workbooks will be open already, and nothing else. Disregard this open workbook and personal book
If wb.Name <> "PERSONAL.xlsb" AND wb.Name <> "consolidation.xlsm" Then
totalValue = totalValue + Worksheets(sht).Cells(R, C)
End If
Next wb
'populate the cell with the total of the corresponding cells
cell.Value = totalValue
'change cell colour to show the above step worked
cell.Interior.ColorIndex = 5
End If
'move on to next cell in worksheet
Next cell
'move on to next sheet in the workbook
Next ws
Application.ScreenUpdating = True
End Sub

How to loop through cells in a sheet to search another sheet?

I need to search "Check" Sheet for values from "Text" sheet.
How can I create a loop for "Text" sheet from cell value A2 to A4 one by one.
I have created below code
Option Explicit
Dim i As Integer
Dim WS, W As Range
Sub Search_fn()
Set WS = Range("B2")
WS = Application.WorksheetFunction.Search(Sheet2.Range("A2"), Range("A2"), 1)
End Sub
This shows 1004 error and I am also not able to crate the loop for all values.
Sheet "Check"
Sheet "text"

Update all links at once

I have a Workbook with many sheets almost all of them have a hyperlink to cell A1 in one specific sheet named 'HK 2017'. I want to change the name of the hyperlinked sheet from 'HK 2017' to 'HK'. And also update all links at once, so that they could work with the new name of the sheet.
Thanks for help.
Loop through the sheets in the worksheet. Excel VBA looping through multiple worksheets
In every sheet, loop through the cells in the used range. Excel VBA iterate over all used cells and substitute their values
Change their hyperlink values. changing a wildcard in an excel hyperlink with vba or Excel VBA Get hyperlink address of specific cell
Party like it's your birthday - https://www.youtube.com/watch?v=5qm8PH4xAss
Here is my solution. In all worksheets of the current workbook I simply replace a given string in the formula for a different one
Public Sub edit_links()
Dim iSheet As Worksheet
Dim old_text as string
Dim new_text as string
old_text = "='\\C\client\XYZ\[old_excel_file.xlsm]Sheet1'"
new_text = "=Sheet1"
For Each iSheet In ThisWorkbook.Sheets
'Debug.Print isheet.Name
Call update_all_cell_formulas_in_sheet( _
isheet, _
old_text, _
new_text)
Next iSheet
End Sub
private Sub update_all_cell_formulas_in_sheet(in_sheet As Worksheet, in_search As String, in_replace As String)
Dim counter As Integer
Dim iCell As Range
counter = 0
For Each iCell In in_sheet.UsedRange
If InStr(iCell.Formula, in_search) > 0 Then
counter = counter + 1
'Debug.Print iCell.Parent.Name, iCell.Address, iCell.Formula
iCell.Formula = Replace(iCell.Formula, in_search, in_replace)
'Debug.Assert counter Mod 100 <> 0 ' stop the code every 100 changes
End If
Next iCell
update_all_cell_formulas_in_sheet = counter
End Sub

VLookup a value in workbook with code in another workbook

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

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

Resources