Macro Explanation - vba

I was looking into how to create a shortcut with the help of VBA. The macro would basically allow me to filter the range based on cell's value. I found this macro on the internet
Public Sub FilterOnCellValue()
Dim nField As Long
With ActiveCell
nField = .Column - .CurrentRegion.Cells(1).Column + 1
.CurrentRegion.AutoFilter Field:=nField, Criteria1:=.Value
End With
End Sub
The code works fine, but I have a hard time trying to understant how the dude create. So what I know so far is the guys is creating a variable. but for some reason the variable is not in a string format but in "long" and the code works perfectly when I filter based on text in a cell. I thought that long can only be used for numbers, correct me if I am wrong (which i think I am:)). Secondly. whats up with .column - .currentregion. cells.....+1? I real have no idea what he did there.
Would really appreciate some help here. the forum has been very useful to me so far.

The secret to understanding anything is to break it into parts
Anyways, the documentation of Autofilter states that
Public Sub FilterOnCellValue()
Dim nField As Long
With ActiveCell
'.Column: Column Number i.e A=1,B=2 etc
'.CurrentRegion.Cells(1).Column: Gets the col No of the firstcell of the data region
nField = .Column - .CurrentRegion.Cells(1).Column+1
'Autofilter takes column number as the parameter
'see example below
'nField: gets the col number of the filter value within the region
' leftmost field is 1 hence +1
.CurrentRegion.AutoFilter Field:=nField, Criteria1:=.Value
End With
End Sub
for e.g if your data is in this format
A B
1 ID Value
2 1 Apple
3 2 Orange
4 3 Banana
5 4 Apple
6 5 Banana
Lets say you click on cell B5(Apple) and run the macro then
The macro first gets the column number of the selected cell =2
checks which column the current region's (A1:B6) first cell(ID) is in =1
calculate value in Step 1-Step 2 to get which column the selected value lies in, with respect to the region (A1:B6) , the idea is using the .column as reference to find out the column number of selected value within the region result of the step:2-1+1=2
Filters the column number passed from step 3(in our example value is 2) of the region A1:B6 for the selected value(Apple)
Hope this helps

Related

Find cell value, match, cut, move, ...vba

I am a beginner in VBA.
I have components which always consist from 2 parts. (Rotor and a stator, each has its own number). When work is with them it can be damaging some of these parts, however it is necessary to keep a list of damaged parts, where the result is inventory e.g. 200 rotors, stators 150 with different numbers. Before I could scrap it, I need to complete them as proper sets. I.e. rotor "a" stator "a", "b" with "b", etc. It's crazy to work with many numbers to compare them, copy …to find the result of sets qty.
It is possible to solve it with Macro, what I try to do, but I was stuck.
What is the task: In the column "A" I have a list of all damaged parts (mix of rotors, stators different numbers). In the column "C" an information only with help of VlookUP, what should be a counterpart number.
What do I need to solve: In row 5, column. „A“ I have component number , but I know that in the same column, somewhere from row 6 to xx I have a counterpart. What I need is … according to information from column C, same row(5) where is info about the counterpart num. to find counerpart in column A, when found, took it out and put into cell B5. Thus,I get a complete set. Then the next row (6), same action. Macro reading num. in „C“,searching in „A“, when found, cut, and put to „B“ next row 7,8,9,… The result should be a certain qty of pairs + some single numbers if not second part found.
The problem I have is that cycle is working until always found relared counterpart. If the counterpart in row A is not available (no match betwen C-A), the code will stop on that row.
What I need help with is, that if code did not find the counerpart based to info from C just skip this row, make it red and continue with next row till end, it means stop on first empty cell in C. Thanks a lot to everybody who is helping me.
Dim pn As Range,
Dim a
Dim x
x = 5
Dim i As Long, Dim radek As Long
a = Cells(x, 3)
For i = 1 To 500
Range("A:A").Select
Set pn = Selection.Find(What:=a)
If Not pn Is Nothing Then
pn.Select
End If
Selection.Cut
Cells(x, 2).Select
ActiveSheet.Paste
x = x + 1
Next
End Sub

Macro query spread over multiple-sheets

Wording my question is slightly tricky so I've included screen-shots to make this easier. I have 2 separate spreadsheets which are currently not linked together in anyway. What I've been asked to do is:
For the drop-downs which have a * next to them, have this * drop-down get converted into a acronym (I.e. If it's Home Visit *, then this will be converted to HV), and have it automatically entered into Cell Position X. Please refer to Image 1 then Image 2)
So the user would click on Sheet one, select the relevant drop-down field and then assign how much time that task took. The second sheet would then update itself with this information - it would insert the users name, program and activities. This is where it gets very tricky. Based off the drop-down selection, if it is asterisked (*), then based off the field-type it will convert it into a set acronym which would then be placed in one of the data fields based off the entry date that has been provided.
I designed both spread-sheets and they have macros in the background, but I can't seem to work out how to best perform this. Would you suggest a transpose function which checks firstly the date criteria and then an INDEX(MATCH) function to match the criteria against a pre-defined name-range which converts Home Visit etc. to HV automatically? I'm also unsure of how to insert delimiters for each new entry that is read. If anyone can provide help I would be very grateful.
I'm not 100% sure I understand your question, but here goes:
What about adding a Worksheet_Change event to look for changes in the drop-down's cell, and then converting it to an acronym?
Place the following code inside the sheet of interest:
Private Sub Worksheet_Change(ByVal Target As Range)
'If Cell A1 is changed, put the acronym into A2
If Target.Row = 1 And Target.Column = 1 Then
Cells(2, 1) = GetAcronym(Target.Value)
End If
End Sub
Function GetAcronym(TheText As String) As String
Dim result As String
Dim x As Long
'Always grab the first letter
result = Mid(TheText, 1, 1)
'Get the other letters
For x = 2 To Len(TheText) - 1
If Mid(TheText, x, 1) = " " Then result = result & Mid(TheText, x + 1, 1)
Next x
GetAcronym = UCase(result)
End Function

VBA to return nth row number from a filtered table in excel [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can anyone please help me with finding the absolute row number of nth element after filter is applied in an excel table.
For example, I have filter on and have a visible range of data element. Now 20th (nth) row in this filtered range could be 60th row (absolute sense) when no filters are on. Is there a way to find the absolute row number using VBA?
Simplest method is special cells. See below:
Sub test()
Dim i As Integer, j As Integer, k As Integer
Dim Report As Worksheet
Set Report = Excel.ActiveSheet ' Store the current worksheet in a variable (always a good idea)
Dim visRng As Range ' Creating a range variable to store our table, excluding any rows that are filtered out.
Set visRng = Report.UsedRange.SpecialCells(xlCellTypeVisible) ' Select only rows within the used range that are visible.
Dim r As Range
For Each r In visRng.Rows ' Loop through each row in our visible range ...
MsgBox (r.Row) ' ... and retrieve the "absolute" row number.
Next
End Sub
EDIT
Tom claims this method will not work, but I'm pretty sure it does what you ask. Example:
Here is my original test table--unfiltered so you can see what we're doing.
And then we filter a couple values somewhere in the middle of the table...
Now when we run the script I posted above, our message box will show the "absolute" row number for each unfiltered row. Results are 1,3,4,5, and 7.
As a function I suggest
Function RowNum(Target As Range) As Long
RowNum = Target.Row
End Function
use by entering in a cell =RowNum(E9). If you want the line relative to the table start and your table starts in -say- row 21, just subtract this from the result (you can use the same function to find the row of table start or course) ... e.g. =rownum(A2)-rownum($A$1) ... mind the absolute notation of table header!
If you don't like this as a function, you could use the SelectionChange event to display the row number of the selected cell in the message line (optionally depending on a "debug flag" somewhere in your sheet).
Tne non-VBA approach would be to use the CELL formula ... e.g. =CELL("row",A1)
The answer brought up by #Lopsided wont work, if there are other hidden cells after the nth entry. They would then be added to the absolute position.
This'll work, you have to change n by yourself in the script. Changing that shouldn't be to hard. If you have any questions regarding that, feel free to ask. (;
Sub absoluteRowID()
Dim RowCount, hiddenRows As Integer
'relative position n
n = 5
i = 0
Do While i < n
i = i + 1
If ThisWorkbook.Sheets(1).Rows(i).EntireRow.Hidden Then
'if there is a hidden row, position is incremented
n = n + 1
End If
'if there is no hidden row, nothing happens
Loop
MsgBox (i)
End Sub
HTH

VBA Macro: Trying to code "if two cells are the same, then nothing, else shift rows down"

My Goal: To get all data about the same subject from multiple reports (already in the same spreadsheet) in the same row.
Rambling Backstory: Every month I get a new datadump Excel spreadsheet with several reports of variable lengths side-by-side (across columns). Most of these reports have overlapping subjects, but not entirely. Fortunately, when they are talking about the same subject, it is noted by a number. This number tag is always the first column at the beginning of each report. However, because of the variable lengths of reports, the same subjects are not in the same rows. The columns with the numbers never shift (report1's numbers are always column A, report2's are always column G, etc) and numbers are always in ascending order.
My Goal Solution: Since the columns with the ascending numbers do not change, I've been trying to write VBA code for a Macro that compares (for example) the number of the active datarow with from column A with Column G. If the number is the same, do nothing, else move all the data in that row (and under it) from columns G:J down a line. Then move on to the next datarow.
I've tried: I've written several "For Each"s and a few loops with DataRow + 1 to and calling what I thought would make the comparisons, but they've all failed miserably. I can't tell if I'm just getting the syntax wrong or its a faulty concept. Also, none of my searches have turned up this problem or even parts of it I can maraud and cobble together. Although that may be more of a reflection of my googling skill :)
Any and all help would be appreciated!
Note: In case it's important, the columns have headers. I've just been using DataRow = Found.Row + 1 to circumvent. Additionally, I'm very new at this and self-taught, so please feel free to explain in great detail
I think I understand your objective and this should work. It doesn't use any of the methodology you were using as reading your explanation I had a good idea how to proceed. If it isn't what you are looking for my apologies.
It starts at a predefined column (see FIRST_ROW constant) and goes row by row comparing the two cells (MAIN_COLUMN & CHILD_COLUMN). If MAIN_COLUMN < CHILD_COLUMN it pushes everything between SHIFT_START & SHIFT_END down one row. It continues until it hits an empty row.
Sub AlignData()
Const FIRST_ROW As Long = 2 ' So you can skip a header row, or multiple rows
Const MAIN_COLUMN As Long = 1 ' this is your primary ID field
Const CHILD_COLUMN As Long = 7 ' this is your alternate ID field (the one we want to push down)
Const SHIFT_START As String = "G" ' the first column to push
Const SHIFT_END As String = "O" ' the last column to push
Dim row As Long
row = FIRST_ROW
Dim xs As Worksheet
Set xs = ActiveSheet
Dim im_done As Boolean
im_done = False
Do Until im_done
If WorksheetFunction.CountA(xs.Rows(row)) = 0 Then
im_done = True
Else
If xs.Cells(row, MAIN_COLUMN).Value < xs.Cells(row, CHILD_COLUMN).Value Then
xs.Range(Cells(row, SHIFT_START), Cells(row, SHIFT_END)).Insert Shift:=xlDown
Debug.Print "Pushed row: " & row & " down!"
End If
row = row + 1
End If
Loop
End Sub
I modified the code to work as a macro. You should be able to create it right from the macro dialog and run it from there also. Just paste the code right in and make sure the Sub and End Sub lines don't get duplicated. It no longer accepts a worksheet name but instead runs against the currently active worksheet.

Search through column in excel for specific strings where the string is random in each cell

I am working in excel with a datasheet that is 1000 rows and 15 columns. Currently, in one of the columns, I have a lot of data mixed in with people names (see below for an example). I want to see how many times each person's name appears in the datasheet, so I can use it in a pivot table. There is no particular format or order to the way names appear. It is random. Is there a way to code in excel to search through that whole column and give me a count of the amount of times each person's name appears?
Column D
21421Adam14234
2323xxx Bob 66
23 asjdxx Jacob 665
43 Tim 5935539
2394Bob 88
After some trial and error, I can generate a list of names, one per row and place them in a different column for comparison sake, if that makes it easier.
I know you have got your answer but why not use COUNTIF with Wild Cards? You don't need VBA for this :)
See this example
=COUNTIF($A$1:$A$5,"*"&C1&"*")
SNAPSHOT
You don't have VBA tagged, but I don't know if there is a way to do this without it. I've built a custom function below. To implement it, take the following steps.
1) List desired names starting at column E1.
2) Insert this function into VBA Editor
A) Presss Alt + F11
B) Click Insert > Module from menu bar
C) Copy this code into Module
Option Explicit
Function findString(rngString As Range, rngSearch As Range) As Long
Dim cel As Range
Dim i As Integer
i = 0
For Each cel In rngSearch
If InStr(1, cel.Text, rngString.Value) > 0 Then
cel.offset(,-1) = rngString.Value 'places the name in cell to right of search range
i = i + 1
End If
Next
findString = i
End Function
3) In F1 type the following formula
=findstring(E1,$D$1:$D$5)
4) Run the formula down column F to get the count of each desired name.