Remove certain columns from sheet - vba

I have a master sheet, but out of this sheet I only need certain columns to be displayed. Doing it manually is taking a long time and this worksheet is something I have to do once in a fortnight.
Can anyone please suggest VBA code to do this?

Let's say you need to delete columns numbers 13, 58 and 101, then do as follows:
Sub DeleteColumns()
Columns(101).EntireColumn.Delete
Columns(58).EntireColumn.Delete
Columns(13).EntireColumn.Delete
End Sub
For keeping the original column numbers, make sure you delete them from the highest to the lowest. Note that columns are numbered from 1 (which is "A") onwards.
If you don't want to delete the columns, but just hide them, then use the Hidden property:
Sub HideColumns()
Columns(13).EntireColumn.Hidden = True
' ... etc.
End Sub

You could go as follows:
Sub ColumnsDelete()
Range("A1, E1, AH1").EntireColumn.Delete
End Sub
Sub ColumnsHide()
Range("A1, E1, AH1").EntireColumn.Hidden=True
End Sub
Where you simply have to type columns headers followed by any row number (I chose "1" for simplicity)

Related

Excel VBA Compare cell value to list and overwrite value in separate sheet

In a workbook I have, users either manually enter an account code or select one from a list and the account codes are placed in column C (C7:C446) in a sheet called "JE". The account codes look like this ####### - ### - ## - ######. In column D (D7:D446) in sheet "JE", there is a formula that captures the last 6 digits of the account code. In a sheet called "required_refs", there is a list of 6 digit codes in column A. If the value in the D column in sheet "JE" equals any of the values in column A of "required_refs" sheet, I would like the value in the D column cell to overwrite the cell value in cell D1 in a separate sheet called "references" (I know that may have been confusing, sorry)
Example: if the value of D25 matches any of the values listed in column A of sheet "required_refs", upon double clicking a red colored F25 cell, put the value of D25 (of sheet "JE"), and put it in cell D1 on sheet "references".
I've taken a crack at it as best I know how. I've placed this code in sheet JE:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim project As Range: Set project = Range("D7:D446")
Dim param As Range: Set param = Worksheets("references").Range("D1").Value
For Each cell In project
If project.Value = Worksheets("required_refs").Range("A:A").Value Then
Call gotoRef_ 'macro that simply selects/navigates to the required_ref sheet
project.Value = param
End If
End Sub
Thanks so much in advance for any suggestions on how to complete this. I can elaborate on this further if needed.
This will do what you want:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Range("F7:F446")) Is Nothing Then Exit Sub
Dim varReference As Variant
varReference = Columns("D").Cells(Target.Row).Value2
If Not IsError(Application.Match(varReference, Worksheets("required_refs").Columns("A"), 0)) Then
Worksheets("references").Range("D1").Value = varReference
End If
End Sub
Important Points:
Whenever working with event handlers, always limit the scope of the target range in the first line. Otherwise, it might not work correctly or it could slow done your spreadsheet.
Make sure your JE sheet column D values and required_refs sheet column A values are all either text or numbers. Otherwise the values won't be compared correctly.
Note the usage of Application.Match() instead of WorksheetFunction.Match() to access the worksheet function. This, coupled with the use of a Variant type variable, allows us to trap the error that occurs if the match fails.
You can always do this on the sheet. Consider the MATCH function. See here for how to use MATCH.
Or another great tool if you're searching for something in a table associated with a value in another column (not your case I don't think)--VLOOKUP formula. Place this formula in the D cell of the sheet you want to place the numbers in. VLOOKUP is in the following format:
=vlookup(lookup value,table_array,column index number, [range lookup])
The lookup value is the 6 digit code you're looking for (on the JE sheet)
The table_array is simply selecting the values you want to search for (required_refs sheet)
The column index number would be one, since the table only has 1 column. It's basically the column number of the value you're looking for.
And range lookup is for if you think there might be more than one place where it matches.
For your case I think it would look like this:
=vlookup('JE'!D1,'required_refs'!A1:A,1,FALSE)
Then just lock the values you want to keep and click and drag down.
Explanation for VLOOKUP here

Excel VBA: How to change value of cell in last used column?

I am new to VBA and am trying to locate the last used column (changes monthly) and change the second row cell in that column to "Apple." The values in the last used column start from row 5, but I need to change row 2. Can anyone help? This the code I have come up with, I understand it's flawed:
Sub NameCell()
.Cells(5, Columns.Count).End(xlToLeft).Column.Select
.FormulaR3C1 = "Apple"
End Sub
Sub NameCell()
With ActiveSheet
.Cells(2,.Cells(5, .Columns.Count).End(xlToLeft).Column).Value = "Apple"
End With
End Sub

Using an Autofilter function for multiple criteria with cases

I have a sheet, where I would like to filter the blank rows in column T and U.
I have certain cases to be considered.
I have few missing rows and have denoted them as missing in column S. If they are missing, I don't want them to be considered for filter condition. In Default they are blank.
The other case is, any one of the rows in column T and U are found blank, has to be filtered. IF both columns are blank, they also have to be filtered.
I have attached two images for reference. Could anyone suggest me how I could do it ? I am a beginner in VBA, Any lead would be helpful.
Sub FC()
Dim ws As Worksheet
Set ws = Sheets("FC")
With ws
.Range("A5:T1000").autofilter Field:=20, Criteria1:="=", Operator:=xlFilterValues
End With
End Sub
I tried the above code, It works with column T.
How can I include multiple criteria? Because with my cases, with column S as missing, I don't need to consider the complete row. And with my T and U, both blank or any one is blank, then I need them to be filtered.
This is how my sheet looks like in the beginning.
I would like to have a code, in such a way that, I want to filter the column T and S with blank rows, any of the rows in column T and U are found blank,
then I would like to filter them.
Ok so here's how you can achieve your custom filtering using a helper column. Let's take column Z for this mission.
Sub FC()
With Sheets("FC").Range("Z5:Z100")
.EntireColumn.Hidden = True ' <-- optional, to hide the temp column
.Formula = "=AND(S5<>""Missing"",OR(ISBLANK(T5),ISBLANK(U5)))"
.AutoFilter 1, True
End With
End Sub

Select the last cell in a Word table

I'm trying to figure out a way to select the last cell in a table in word. I have a document that auto-generates with one table, in which all blank cells are merged into an empty column in the bottom-right. Is there code that can select the bottom-right cell in a table?
As your table contains merged cells you may find that referring to the column count gives you an error.
Use this instead:
Private Sub SelectLastCell()
With ActiveDocument.Tables(1).Rows.Last
.Cells(.Cells.Count).Range.Select
End With
End Sub
Edit:
To select the last cell of the last column simply reverse the logic, like so:
Private Sub SelectLastCell()
With ActiveDocument.Tables(1).Columns.Last
.Cells(.Cells.Count).Range.Select
End With
End Sub

VBA - EXCEL Remove columns except specified range

I was looking for answers however I can't find one so specific.
I am trying to write macro which will be easy to use for people without any programming knowledge.
So we use pricing template where you can see prices for many different countries. I want to create a macro which will copy whole tab and remove unwanted columns depends from for which country it is creating file. (Needed to preserve formulas, I still want to have all the calculation not values).
So first few columns will stay since they are common for all countries, and then all the columns except selected range should be deleted. Ranges are specified in separate tab and will be stored in array.
Example:
Belgium
First Column: CJ
Last Column: CQ
So let's say in first loop first column and last column values are stored, and I want macro remove columns from H to CI and then from CR to HF.
However in next loop first and last will change so delete ranges have to recalculate.
I tried with formulas ASC and CHR but it doesn't work with two letters codes.
Well, if you already know the ranges you want to use, a subroutine like this could remove a range of columns, minus an exception range.
I'm just looping through the columns and checking for an intersection. If there is no intersection between the column being tested and the exception range, we add it to the list of columns to be deleted.
Public Sub RemoveColumnsExcept(removeRange As Range, exceptRange As Range)
Dim deletionRange As Range
Dim columnRange As Range
For Each columnRange In removeRange.Columns
If Intersect(columnRange, exceptRange) Is Nothing Then
If deletionRange Is Nothing Then
Set deletionRange = columnRange
Else
Set deletionRange = Union(deletionRange, columnRange)
End If
End If
Next columnRange
If Not deletionRange Is Nothing Then
deletionRange.Delete xlShiftToLeft
End If
End Sub
Public Sub Test()
RemoveColumnsExcept Sheet1.[B:J], Sheet1.[G:I]
End Sub
You could use named ranges to keep track of the columns you want deleted. That or column headers and a loop looking for some value like country code in a specific row.