How to make Column Dynamic in below mentioned VBA - vba

If Worksheets("Data").Range("D5").value = 0 Then
Columns("K").EntireColumn.Hidden = True
Else
Columns("K").EntireColumn.Hidden = False
End If
Sir, I have the above code where Column "K" is hide/unhide based on the cell "D5" of another sheet. But when I Add or Delete Column in my excel then my desired column no. shift to "L" or "J" but column "K" static in VBA and hide by this code which should not happen. How this column "K" automatically change when a column delete or add in excel

I would suggest that you put a name ("Named Range") to the top cell of the column you want to show/hide. Then you can access this named Range in the code.
Assuming you defined the name "Homeloan" on Cell K1: write
Range("HomeLoan").EntireColumn.Hidden = False
Note that you should always qualify the Excel objects so that it is clear which worksheet you want to access, but that's not part of your question

If you don't have problem to unhide all the columns before searching for the word "Homeloan" this should work even if you delete or add columns.
Sub test()
Dim lcol As Long
With Worksheets("Data")
.Columns("A:AC").EntireColumn.Hidden = False 'Unhide all the columns first
'This only works if the column with the word homeloan is not hidden.
lcol = Application.WorksheetFunction.Match("Homeloan", .Range(.Cells(1, 1), .Cells(1, .Cells(1, .Columns.Count).End(xlToLeft).Column)), 0) 'Find last column in row 1. Then create a range to look for the word "Homeloan". Last, return the current column number where Header "Homeloan" exists.
If .Range("D5").Value = 0 Then
.Columns(lcol).EntireColumn.Hidden = True
Else
.Columns(lcol).EntireColumn.Hidden = False
End If
End With
End Sub

Related

VBA - how to use macro button for multiple boxes

I am new to VBA and macro. I will try to explain what I am trying to create then I will explain what problem I have with it.
There are two sheets in my Excel; 'Sheet 1' and 'Sheet 2'.
Sheet 1 is full of data. This data goes from column A to AK and there are 4206 rows.
Sheet 2 only consist an input cell box with a 'GO' button next to the box. The button is assigned to a macro.
What do I want to create?
In the input cell box I type something like 'GB' and then press the 'GO' button. The 'GO' button will look through Sheet 1 for cells with 'GB' in them. There are two particular columns that could have 'GB' in them; one of them is column K and one is column L. The 'GO' button will look in those two columns for 'GB' and filter the rows.
Important note: I don't want to design a macro so that they will look for 'GB' in column K and column L. Instead I want them to look for 'GB' in column K or column L.
What did I create?
I designed a macro and assigned it to the 'GO' box. This is the code that I put in:
Option Explicit
Sub Macro1()
'
' Macro1 Macro
'
Sheets("Sheet 1").Select
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
Range("A12:AM4216").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _
Range("A1:AK2"), Unique:=False
End Sub
What works with the code? And what is the problem?
The code will return rows that has 'GB' in column L. This is great. However, I am looking of ways how to change the code so that it will return rows that has 'GB' in column K or column L.
Any advice on this please?
Thank you.
I think something like this should probably do it. I was a little confused on whether the 'GB' was something that would vary or if it would be the same every time, so I included the option for both (by default the code assumes it's static). I also didn't know if you wanted it case-sensitive, so by default, it is NOT case sensitive (to make it case-sensitive, remove the LCase functions).
Sub Macro1()
Dim ws As Worksheet
Dim firstRow As Long, lastRow As Long
Dim firstCol As String, secondCol As String
Dim findStr As String
Dim x As Long
'define worksheet to check
Set ws = ActiveWorkbook.Sheets("Sheet1") 'or whichever sheet
'define search string to check for based on static value
findStr = "GB"
'define search string to check for based on cell value
'findStr = ws.cells("A1") 'or whichever cell
'define start and end rows to loop through
firstRow = 12
lastRow = 4216
'define columns to check
firstCol = "K"
secondCol = "L"
'turn off screenupdating
Application.ScreenUpdating = False
'unhide rows in range
ws.Range(ws.Rows(firstRow).EntireRow, ws.Rows(lastRow).EntireRow).Hidden = False
'loop through the rows
For x = firstRow To lastRow
'if either cell has the search string in it (regardless of case)...
If InStr(LCase(ws.Range(firstCol & x)), LCase(findStr)) Or InStr(LCase(ws.Range(secondCol & x)), LCase(findStr)) Then
'...do nothing
Else
'...otherwise, hide the row
ws.Rows(x).EntireRow.Hidden = True
End If
Next x
'turn screenupdating back on
Application.ScreenUpdating = True
End Sub
Please note that like Cyril mentioned above, this is not a true filter: it just hides rows that don't match the specified criteria.

how to use a cell value in an active column in a named row range in VBA

In a worksheet, there are two named ranges, each of which only contains a row, e.g. Range1 = Range("B5:H5") and Range2 = Range("B9:H9"). My question is: how can I reference a cell in Range1, say C5, and a cell in Range2, say C9 in VBA so that I can do something with the values in these two cells? The VBA should only run for the active column. Thank you in advance.
Maybe you should see this link.
How to avoid using Select in Excel VBA macros
As Siddarth stated,
Two Main reasons why .Select/.Activate/Selection/Activecell/Activesheet/Activeworkbook etc... should be avoided
It slows down your code.
It is usually the main cause of runtime errors.
How do we avoid it?
1) Directly work with the relevant objects
Consider this code
Sheets("Sheet1").Activate
Range("A1").Select
Selection.Value = "Blah"
Selection.NumberFormat = "#"
This code can also be written as
With Sheets("Sheet1").Range("A1")
.Value = "Blah"
.NumberFormat = "#"
End With
2) If required declare your variables. The same code above can be written as
Dim ws as worksheet
Set ws = Sheets("Sheet1")
With ws.Range("A1")
.Value = "Blah"
.NumberFormat = "#"
End With
Use can
Range1.offset()
method to refer adjacent cell
You can refer here for detail .
Would this work?
Range("Range1").Cells(1, 1).Select 'Selects Range("B5") - first cell in Range1
Range("Range1").Cells(1, "A").Select 'Also selects first cell in the named range
'copies cell 2 (C9) from Range2 into cell 2 (C5) of Range1; .Cells(row, col)
Range("Range1").Cells(1, 2) = Range("Range2").Cells(1, 2)
By using the Cells method, you can specify the appropriate row using Range1.Row (and Range2.Row), and the appropriate column using (if I understand you correctly) Selection.Column.
So perhaps something like:
Dim Range1 As Range
Dim Range2 As Range
Set Range1 = Range("B5:H5")
Set Range2 = Range("B9:H9")
'Display the value in row 5 for the current column
MsgBox Cells(Range1.Row, Selection.Column).Value
'Display the value in row 9 for the current column
MsgBox Cells(Range2.Row, Selection.Column).Value
'Change row 9 to be the value from row 5
Cells(Range2.Row, Selection.Column).Value = Cells(Range1.Row, Selection.Column).Value
'Display the updated value in row 9 for the current column
MsgBox Cells(Range2.Row, Selection.Column).Value

How to automatically hide/unhide rows based on cell value VBA

I have a worksheet with multiple pull-down lists in Col A. The pull downs change values of the cells below in Column A to either "Skip" or some other value. I am looking to hide the rows with "Skip" in Column A, as well as the one row below the cells with value "Skip". I've got this to work on another sheet with columns of horizontally oriented data, but have gotten stuck with the data oriented vertically (in one column). I've been able to get the rows to hide, but they will not unhide when the cell value is no longer "Skip".
Here's the code I've got running currently:
`Sub Worksheet_Change_Hiding()
Dim rng As Range
Dim s As String
s = "Skip"
Application.EnableEvents = True
For i = 1 To 50
Set rng = Cells(i, 1)
If rng.EntireRow.Hidden = 0 Then
If rng.Value = s Then rng.EntireRow.Hidden = 1
Else
If rng.Value <> s Then rng.EntireRow.Hidden = 0
End If
Next i
End Sub`
Screen Shot

Deleting duplicates in excel using VBA

i'm fairly new to VBA and could do with a bit of help. I've looked online and i've found a few bits of code but have been unable to amend to my needs.
I'm trying to create a macro that will enable me to see if their are any duplicate text between column A and B and if the text in column A matches Column B then we will need to delete the entire row. The columns are on the same sheet
I am trying to create a loop that will do this. I must also point out that the length of the list does increase every week
I would appreciate any help
Thank you
Hi try in your code VBA:
Sub DeleteRowWithContents()
'========================================================================
' DELETES ALL ROWS FROM A2 DOWNWARDS WITH THE WORDs "Record Only" IN COLUMN D
'========================================================================
Last = Cells(Rows.Count, "D").End(xlUp).Row
For i = Last To 1 Step -1
If (Cells(i, "D").Value) = "Record Only" Then
'Cells(i, "A").EntireRow.ClearContents ' USE THIS TO CLEAR CONTENTS BUT NOT DELETE ROW
Cells(i, "A").EntireRow.Delete
End If
Next i
End Sub
you can update this code for your problem!
I use this when i need deletes all rows from a2 downwards with the words "record only" in column d.
Maybe try this:
Sub DeleteRowWithContents()
Dim ColumnAValue As String
Dim ColumnBValue As String
Dim xlWB As Worksheet
Set xlWB = ActiveWorkbook.ActiveSheet 'If it isn't the active sheet use second row:
'Set xlWB = ActiveWorkbook.Sheets("NameOfSheet") 'Change to the name of your sheet
For i = 1 To EOF 'This goes through the whole document to the last row automatically, EOF means "End Of File"
ColumnAValue = xlWB.Cells(i, 1).Value 'row i, column "a"
ColumnBValue = xlWB.Cells(i, 2).Value 'row i, column "b"
If (ColumnAValue = ColumnBValue) Then
xlWB.Range(ColumnAValue).Select
Selection.EntireRow.Delete 'NOTE!!
End If
Next i
End Sub
NOTE: I'm not too sure if this works, can't test it right now. IF it doesn't, try this instead:
EntireRow.Select
Selection.Delete

Find If cell matches in another sheet and count/sum instances

I have been using simple excel array formulas to count certain values on a master sheet but now at the point where I have too many formulas in my document and excel is crashing.
Therefore, I would like to create a macro that can do the same task. I would like to have the code do the following:
IF the activecell in Sheet1 matches to any cell in a column(or range) in Sheet2,
AND IF the cell in the same row in an adjacent column in Sheet2 is not blank,
THEN count all the instances that specific string appears in Sheet2 column A
AND place the value 2 columns to the right of the original active cell in Sheet1.
Here is the original array formula I was using:
=SUM(IF(Sheet1!$A8=Sheet2!$A:$A,IF(SalesF_SignUp_data!$C:$C>1,1,0)))
The formula above is taking the cell A8 in Sheet1 and checking if it matches to any cell in Sheet2 column A,
AND making sure that column C in Sheet2 is not blank in the same row.
If this is TRUE then "add 1" for all the instances
AND place that value in Sheet1.
I believe the best way to do this is a For Next Loop but haven't been able to execute any successful code based on examples I've found.
Im happy to explain further if needed. Since I dont have a reputation of 10 I cant attach images but am willing to send if needed.
This is set up to run for all the cells you've selected in column A of sheet 1.
It looks in Sheet2 column A for the value on Sheet1 column A, then in Sheet1 column B, displays how many times the value appeared in Sheet2 column A along with a value in the same row of column C.
If the answer is helpful, please mark it as such. :-)
Option Explicit
Sub countinstances()
Dim result, counter, loopcount, tocomplete, completed As Integer
Dim findtext As Variant
Dim cell, foundcell, nextcell As Range
'Checks to make sure the sub isn't accidentally run on an invalid range
If ActiveSheet.Name <> "Sheet1" Or ActiveCell.Column <> 1 Or Selection.Columns.Count > 1 Then
MsgBox ("Please select a range in column A of Sheet 1.")
Exit Sub
End If
'In case of selecting the entire column A, curtail the number of blank cells it runs on.
tocomplete = Application.WorksheetFunction.CountA(Selection)
completed = 0
'For each cell in the selected range, searches Sheet2, Column A for the value in the selected cell
For Each cell In Selection
If completed = tocomplete Then Exit Sub
If cell.Value <> "" Then completed = completed + 1
findtext = cell.Value
result = 0
Set foundcell = Sheets("Sheet2").Range("A1")
'Uses the count function to determine how many instances of the target value to search for and check
loopcount = Application.WorksheetFunction.CountIf(Sheets("Sheet2").Range("A:A"), findtext)
'Skips the loop if the target value doesn't exist in column A
If loopcount = 0 Then GoTo NotFound
'For each time the target value was found, check the cell in column C. If it's not blank, increment "result"
For counter = 1 To loopcount
Set nextcell = Sheets("Sheet2").Range("A:A").Find(what:=findtext, lookat:=xlWhole, after:=foundcell)
If nextcell.Offset(0, 2).Value <> "" Then
result = result + 1
End If
Set foundcell = nextcell
Next
'Put the result in column B of Sheet1
NotFound:
cell.Offset(0, 1).Value = result
Blanks:
Next
End Sub