My other macro scrapes mutual fund sizes from web and returns the values in Worksheets("Updater").Cells(xx,4) (so column C). The macro scrapes also the date in which the fund has been updated on morningstar and returns it in column F on the same sheet. I've got 83 fund names in column A.
On a sheet called "Tracker" I've got the fund names transposed. They start from cell (1,4) and go to (1,86). In column B I've got DATEVALUE of dates in column C. There're some issues with the date formats so I'll just hide the column B later.
The below macro works as it is, but when you uncomment lines 11 and 22, it doesn't work as intended anymore. Idea is to look at the fund sizes on sheet "Updater" and return the fund size to the corresponding date on sheet "Tracker". As said, this works.
However, with the nested if statement, I'd want to modify the macro so it would keep all the cells that contain other than "-" untouched. This way I would start to cumulate the fund size data when the macro is executed on a daily basis and doesn't overwrite the old fund sizes with "-".
Now the macro flips the funds who knows where and I simply can't solve this nested if statement problem. Is this even the correct/best way to get where I want?
Sub fundSizeTracker()
Dim f As Integer
Dim numRows As Integer
numRows = 86
f = 2 'Sheet fund names & sizes
For m = 2 To 4 'Sheet row number, starting at rowNo 2
For i = 4 To numRows 'Sheet column number (set to include all 83 funds)
' If Worksheets("Tracker").Cells(m, i) = "-" Then
' Are Datevalues same? 'Tracker datevalue 'Updater datevalue
If StrComp(Worksheets("Tracker").Cells(m, 2).Value, Worksheets("Updater").Cells(f, 13).Value) = 0 Then
Worksheets("Tracker").Cells(m, i) = Worksheets("Updater").Cells(f, 4).Value
Else
Worksheets("Tracker").Cells(m, i) = "-"
End If
If f = numRows - 1 Then
f = 2
End If
f = f + 1
' End If
Next i
Next m
End Sub
Related
I have a for loop that iterates through each sheet in my workbook. Each sheet is identical for most purposes. I am making an overview sheet in my workbook to express the results from the data in the other sheets(the ones that are identical).
There are 11 vehicles, each with their own sheet that has data from a test from each day. On any given day there can be no tests, or all the way to 30,000 tests. The header of each column in row 47 states the date in a "06/01/2021 ... 06/30/2021" format. The data from each iteration of the test will be pasted in the column of the correct date starting at row 49.
So what my overview page needs to display is the data from the previous day. In one cell on my overview there is a formula for obtaining just the number of the day of the month like 20 or 1 etc. Using this number, the number of the day is the same as the column index that the previous day's data will be in conveniently. So in my for loop I want to have a table that has the name of each sheet in column B, in column C I want to display the total number of tests done in that day(not the sum of all the data), in column D I need the number of tests with a result of 0, in column E I need the number of tests that have a result above the upper tolerance, and in column F I need the number of tests that have a result below the lower tolerance minus the result in column D.
I've been playing with the Application.WorksheetFunction.Count and CountIf functions but I keep getting 0 for every single cell. I made two arrays for the upper and lower tolerance values which are type Longs called UTol and LTol respectively. TabList is a public array that has each of the sheet names for the vehicles stored as strings. finddate is an integer that reads in Today's day number which is yesterday's column index. I've included a picture of the table in question and my for loop code:
finddate = Worksheets("Overview").Range("A18").Value
For TabNRow = 1 To 11
startcol = 3
Worksheets(TabList(TabNRow)).Activate
Debug.Print (TabList(TabNRow))
'Total number of tests done that day
Worksheets("Overview").Cells(startrow, startcol).Value = Application.WorksheetFunction.Count(Range(Cells(49, finddate), Cells(30000, finddate)))
startcol = 4
'Total number of 0 results, this used to get the number of 0's from each sheet but that row has since been deleted
Worksheets("Overview").Cells(startrow, startcol).Value = Worksheets(TabList(TabNRow)).Cells(48, finddate).Value
startcol = 5
'Total number of results above tolerance
Worksheets("Overview").Cells(startrow, startcol).Value = Application.WorksheetFunction.CountIf(Range(Cells(49, finddate), Cells(30000, finddate)), ">" & UTol(TabNRow))
startcol = 6
'Total number of results below tolerance
Worksheets("Overview").Cells(startrow, startcol).Value = Application.WorksheetFunction.CountIf(Range(Cells(49, finddate), Cells(30000, finddate)), "<" & LTol(TabNRow))
startrow = startrow + 1
Next TabNRow
```
No need to select/activate sheets when referencing them. See: How to avoid using Select in Excel VBA
Something like this should work:
Dim wsOv As Worksheet, wsData As Worksheet, rngData As Range
Set wsOv = ThisWorkbook.Worksheets("Overview")
finddate = wsOv.Range("A18").Value
For TabNRow = 1 To 11
Set wsData = ThisWorkbook.Worksheets(TabList(TabNRow))
Set rngData = wsData.Range(wsData.Cells(49, finddate), _
wsData.Cells(Rows.Count, finddate).End(xlUp))
Debug.Print wsData.Name, rngData.Address 'edited
With wsOv.Rows(2 + TabNRow)
.Columns("C").Value = Application.Count(rngData)
.Columns("D").Value = Application.CountIf(rngData, 0)
.Columns("E").Value = Application.CountIf(rngData, ">" & UTol(TabNRow))
.Columns("F").Value = Application.CountIf(rngData, "<" & LTol(TabNRow)) _
- .Columns("D").Value
End With
Next TabNRow
I have two sheets :
Sheet 1 consist of :
Sheet 2 consist of :
And the output should show in M column in Sheet1. I am attaching the sample output here :
So,what I have here is ID in Sheet 1, for eg : ID 'US' has Abhay,Carl and Dev
and in Sheet3, I have names in column and ID in Rows.
What i want is my Sample output column should populate using macro based on matched values from Sheet3
I am using below logic but something is going wrong :
For i = 2 To 10
j = i + 1
If ThisWorkbook.Sheets("Input").Range("N" & i) = ThisWorkbook.Sheets("Sheet3").Range("A" & i) And ThisWorkbook.Sheets("Input").Range("K" & i) = ThisWorkbook.Sheets("Sheet3").Range("B1") Then
ThisWorkbook.Sheets("Input").Range("O" & i) = ThisWorkbook.Sheets("Sheet3").Range("B" & j)
End If
Next i
Since you asked for a VBA solution, please see the code below.
Dim colLen As Integer
Dim i As Integer
Dim colPt As Integer
Dim rowPt As Integer
' Counts number of rows on Sheet 1, column B.
colLen = Sheets(1).Cells(Rows.Count, "B").End(xlUp).Row
' Loops through all names on Sheet 1.
For i = 2 To colLen
' Retain US or NA ID for blank cells.
If Sheets(1).Cells(i, 1) <> "" Then
If Sheets(1).Cells(i, 1) = "US" Then
colPt = 2
Else
colPt = 3
End If
End If
' Find name on Sheet 2 and set row.
rowPt = Sheets(2).Range("A:A").Find(Sheets(1).Cells(i, 2)).Row
' Add ID from Sheet 2 to Sheet 3
Sheets(1).Cells(i, 3) = Sheets(2).Cells(rowPt, colPt)
Next i
Assumptions:
Sheet 1 is the main worksheet, sheet 2 has the lookup data.
All names in the lookup data are unique.
I would recommend including the ID in every row instead of treating it as a heading but that's preference. There are formula solutions that would work for this as well if you want to skip VBA.
There are a few ways to approach this. Below is one of them:
NOTE: for simplicity, I have kept my data on one sheet. You can amend the below formulas as your data is on 2 sheets. Saying that, I have used the same columns as you have in your query
Solution:
Have a "holding column". In my example, I used column J as the holding column (you can hide this column if you want). In J2, type the following formula: =IF(ISBLANK($K2), $J1,$K2). Copy the formula down to all used rows. Then copy the following formula in M2: =VLOOKUP($L2,$A$3:$C$8,IF($J2="US",2,3),FALSE). As per before, copy the formula down to all used rows. This should give you your results
I made a function that counts the number of items in a given month.
Column A is the month, and Column B is the number of items in that month.
Cell B1 has:
=countItems(A1)
Excel data:
Code:
Function countItems(month)
Application.Volatile
Dim count As Integer
If Not (month = 0) Then
count = 0
Do While Not (Cells(month.row + count + 1, 3) = 0)
count = count + 1
Loop
countItems = count
Else
countItems = ""
End If
End Function
I dragged the formula down from B1 to B500 and it works properly for every month. The formula returns nothing if there is no month in the corresponding A cell.
I have multiple sheets using the same formula on similarly-structured data sets.
Whenever the values in column B update for this Sheet 1, the other sheets will change too. However, Sheet 2 will update using Column C from Sheet 1.
If I have Sheet 2 recalculate, Sheet 1 will update using Column C from Sheet 2.
The function counts the number of items in a given month by checking how far down it can read in Column C before it finds the blank cell, indicating that the month is over.
Sheet 2 has 1 item in the first month, but it will still return 3 due to Sheet 1 having 3 items (counts Row 1 through 3 and stops at Row 4).
The second month of Sheet 2 begins on Row 3. But since the function is reading Column C from Sheet 1, it will run into the blank cell after counting 1 more item (counts Row 3 and stops at Row 4). Therefore no matter how many items are in Sheet 2 Month 2, it will return 1.
The function always uses the correct Column A, and only displays a number in Column B where there is date in Column A.
The consequence is that only 1 sheet can have the correct values, and doing that disrupts the other sheets.
I cannot solve this at the moment because I am new to VBA.
I have thought of making all of the function's cell references include a self-reference to the current cell's sheet, but I don't know how to do that and I don't know if it would work.
Edit: I couldn't make it work this way, but Application.Caller.Offset() with relative cell position worked as a solution. I am still wondering if there is a way to use absolute cell position though.
The sheets are not grouped together.
it's because there's a "time-space shift" between the range passed to the function and the range "felt" as the "caller" one by the function
you can see this behavior by modifying the function code as follows
Function countItems(month)
Application.Volatile
Dim count As Integer
Dim r As Range
Dim p As Variant, a As Variant
Set r = Application.Caller '<~~ retrieve the actual "calling cell" of the current function "instance"
p = r.Parent.Name
a = r.Address
MsgBox p & " vs " & month.Parent.Name & vbCrLf & a & " vs " & month.Address '<~~ compare the function "calling cell" vs the "passed cell"
If Not (month = 0) Then
count = 0
Do While Not (Cells(month.Row + count + 1, 3) = 0)
count = count + 1
Loop
countItems = count
Else
countItems = ""
End If
End Function
and you'll see msgboxs prompts showing you differences between the function "calling cell" and "passed cell" addresses and/or sheets
so to avoid this behavior you could rely on the "calling range only", like follows:
Option Explicit
Function countItems(month)
Application.Volatile
Dim r As Range
Set r = Application.Caller '<~~ retrieve the actual "calling cell" of the current function "instance"
'the "calling cell" is the one with the called function in its formula, i.e. in column "B" as per your data structure. then ...
If Not IsEmpty(r.Offset(, -1)) Then '<~~ ... the column with dates are one column to the left, and ...
Do While Not IsEmpty(r.Offset(countItems + 1, 1)) '<~~ ... the values to be checked for are one column to the right
countItems = countItems + 1
Loop
End If
End Function
I am trying to use variables obtain from one workbook called "Mapping File.xlsx" as criteria in an INDEX/MATCH search in a different workbook called "Extract.xlsx" (both are Sheet1). The most important thing is that I need to search Column A for PartNumber (string), Column B for GroupCounter (String), and Column C for OperationNumb (String) and return the value found in Column G for ReturnValue (String).
Setting up my variables:
Dim PartNumber, GroupCounter, OperationNumb, ReturnValue As String 'Inputs are strings that are actually pulled from first workbook
PartNumber = Workbooks("Mapping File.xlsx").Worksheets("Sheet1").Cells(2, 1)
GroupCounter = Workbooks("Mapping File.xlsx").Worksheets("Sheet1").Cells(2, 2)
OperationNumb = Workbooks("Mapping File.xlsx").Worksheets("Sheet1").Cells(5, 1)
Trying to use my variables to search a different workbook using INDEX/MATCHING:
Attempt 1
str = "=INDEX(G:G, MATCH(1, (PartNumber=A:A)*(GroupCounter=B:B)*(OperationNumb=D:D),0))"
ReturnValue = Workbooks("Extract.xlsx").Worksheets("Sheet1").Evaluate(str)
Attempt 2
str = "=INDEX(G:G, MATCH(PartNumber & GroupCounter & OperationNumb, Workbooks("Extract.xlsx").Worksheets("Sheet1").Range("A:A") & Workbooks("Extract.xlsx").Worksheets("Sheet1").Range("B:B") & Workbooks("Extract.xlsx").Worksheets("Sheet1").Range("C:C")),0))"
ReturnValue = Workbooks("Extract.xlsx").Worksheets("Sheet1").Evaluate(str)
Attempts 3 - 30
I have tried to declare the ranges and use the variable names for the ranges in the MATCH_array. I have messed with declaring workbooks and worksheets. I have tried using a SUMPRODUCT. I have tried changing my variable types multiple times. I have messed with quotation marks and splitting the string up. I have tried splitting the INDEX and MATCH functions up. I have spent about 6 hours now on the google search to see whats out there, tweaking my code, and retesting and so now I'm looking for how this can be done. I don't want to hardcode the workbook or worksheets in to the INDEX/MATCHING function if I can avoid it due to the amount of times I will be using this capability in my larger code. So I'm looking for a way to pull 3 criteria from one sheet in 3 different cells, store them as strings, and then use those three strings to search through a second workbook to find the row that it occurs on, and use that row to return the value in a different column as a string (all with using as much variable names as possible to avoid much hardcoding). Any suggestions/ideas?
How about using the autofiler?
If there is always only one record matching (or none) the selected criteria, the requested cell in column G should be always in the same row (after filtering out all other rows).
The code is not elegant, but perhaps it would give some ideas. It copies rows matching the criteria to the separate sheet and shows the contents of the first row that matches these criteria.
Sub Makro2()
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Sheets("Results").Delete
ThisWorkbook.Sheets.Add.Name = "Results"
Application.DisplayAlerts = True
Sheets("Arkusz1").Select
Cells.Select
Selection.AutoFilter
Selection.AutoFilter Field:=1, Criteria1:="a" ` use PartNumber inestead of "a"
Selection.AutoFilter Field:=2, Criteria1:="b" `use GroupCounter instead of "b"
Selection.AutoFilter Field:=3, Criteria1:="c" ` use OperationNum instead of "c"
Selection.SpecialCells(xlCellTypeVisible).Copy
Sheets("Results").Paste
Var = Sheets("Arkusz1").Range("G4")
MsgBox Var
Sheets("Arkusz1").Activate
Cells.Select
Selection.AutoFilter
End Sub
Another option is to use the function CONCATENATE to join these 3 criteria and make one string of them and then use VLOOKUP function. In an additional columny put this: =CONCATENATE(cell with PartNumber, cell with GroupCounter, cell with OpetationNum) and then use Vlookup like this =VLOOKUP(cell with cruteria1& cell with criteria2& cell with criteria3;search area;column G relative address number; 0)
B C D E F G H
3 a e m `=CONCATENATE(A1;B1;C1) 1
4 a f n afn 2
5 b g o bgo 3
6 b h p bhp 4
7 c i q ciq 5
8 c j r cjr 6
9 d k s dks 7
10 d l t dlt 8
11
12
13 c j r `=VLOOKUP(A11&B11&C11;$D$1:$G$8;4;0)
I need to merge cells using a formula so that the cells only merge when cells on another tab are filled.
I have 2 tabs with the same amount of columns in each. I want cells a1-d1 to merge in tab 1 when cells a1-d1 in tab 2 are filled and for the value of d1 in tab 2 to be inputted into the newly merged cells in tab 1.
this is what I have:
Excel VBA Methods and Function (Excel Macros) overview
Since you want to change cells i do not believe that you can use a formula (even not a user defined one). Therefore i wrote an excel vba macro for your problem.
FirstRows(): Is the starting point. It loops over 10 rows and calls the other methods
CheckEmptyCellValues(curRow): This method checks for empty cells in tab2 (sheet 2 in excel)
MergeCells(curRow) takes the current row as a number (any integer from 1 to max amount of rows) and merges the cells from column 1 to 4 on Sheet 1 (the first sheet in excel)
Fully working demo tested with 4 columns and 10 rows
Sub FirstRows()
Sheets(1).Select
For curRow = 2 To 11
Merge = CheckEmptyCellValues(curRow)
If Merge = 4 Then
MergeCells (curRow)
cellValue = Sheets(2).Cells(curRow, 4).Value
Sheets(1).Cells(curRow, 1).Value = cellValue
End If
Next
End Sub
Sub MergeCells(curRow)
Sheets(1).Select
Range(Cells(curRow, 1), Cells(curRow, 4)).MergeCells = True
End Sub
Function CheckEmptyCellValues(curRow)
Merge = 0
Sheets(2).Select
For i = 1 To 4
If Len(Cells(curRow, i).Value) > 0 Then
Merge = Merge + 1
End If
Next
CheckEmptyCellValues = Merge
End Function
Below you can see the result. The values from sheet 2 haven been copied to sheet 1 (second image). In Sheet 1 the Cells in a row are merged (in row 2 from Cell A2 up to Cell D2 (A2-D2 is now just one cell) if in the first image (sheet 2) every cell (from column a to column d) in a row had a value.
Bugs in the modified code
There are a few things in the modifiend code that are not possible or could lead to a wrong understanding
Function CheckEmptyCellValues(curColumn)
Merge = 0
Sheets(2).Select
For i = A To d
If Len(Cells(curColumn, 11).Value) > 0 Then
Merge = Merge + 1
End If
Next
CheckEmptyCellValues = Merge
End Function
The line For i = A To d is not possible. If you want to use a loop you have to use numbers: For i = 1 To 4 this would repeat the code between For and Next4 times starting with 1
This line Cells(curColumn, 11).Value is technical correct but misleading. Excel uses the first value after (for the row-index and the second value for the column-index. Both values have to be a number: Cells(4,2).Value returns the Cell value from the 4th. row and the second Column (in the Excel Gui the Cell B4)
Try changing this line For i = A To d to this For i = 1 To 4 and see if that returns the wished result.
Bugs part 2
In your other modification you have some of the same bugs:
The loop For curColumn = A to d needs numbers instead of letters (unless A and d were a variable filled with a number but according to your code sample this is not the case
The line cellValue = Sheets(2).Cells(curColumn, d).Value has the same bug, if d is just the letter d and not something like d = 4 than you can not use it in a loop.
This is the code from your comment:
Sub FirstRows()
Sheets(1).Select
For curColumn = A To d
Merge = CheckEmptyCellValues(curColumn)
If Merge = d Then
MergeCells(curColumn)
cellValue = Sheets(2).Cells(curColumn, d).Value
Sheets(1).Cells(curColumn, d).Value = cellValue
End If
Next
End
Sub Sub MergeCells(curColumn)
Sheets(1).Select
Range(Cells(curColumn, 1), Cells(curColumn, d)).MergeCells = True
End Sub
Be carefull it is not running.