Macro to find and delete column based on cell value - vba

I have two sheets in an Excel workbook. I would like a VBA code to search for the content of cell J19 in Sheet2 and delete the column with the matching cell in Sheet1. I have been searching all around Google to look for some VBA codes, but I haven't found anything yet that works.
Does anybody here know how to do this? I have zero experience in VBA.

You could try this code to perform such a task.
Sub FindMatchAndThenDeleteColumn()
FindContent = Worksheets("Sheet2").Range("J19")
For Each Cell In Worksheets("Sheet1").UsedRange.Cells
If Cell.Value = FindContent Then Columns(Cell.Column).Delete
Next
End Sub
Put the code above in your workbook's module. Note that FindContent and Cell are randomly chosen here, you can use any names. I use
For Each Cell In Worksheets("Sheet1").UsedRange.Cells
to loop through every cell that is in use in Sheet1. It will check everything in the range from cell A1 to the last cell with data (the bottom right-most cell). If the content of cell J19 is a text, you can declare the variable FindContent as a String type, i.e. Dim FindContent As String. If it's a number, you can declare it as a Long type or a Single type or any number type that fits the content. Here I don't declare it which means it defaulting to a Variant type. And since you're a beginner in VBA, you may learn it from Excel Easy. Hope this helps.

Related

Vlookup vba automatisation

I'm a beginner in VBA programmation, I want to create a button to help me search the price of a product from column A of sheet1 and to search for the price of that product from sheet2, column D of the same workbook.
The vlookup formula I use is:
=VLOOKUP(A2;sheet2!A2:G712;4)
My issue is that I have more than 100000 products and I want to use a button to simplify the process.
Change your top row formula to =VLOOKUP(A2;sheet2!$A$2:$G$712;4), select the cell you enetered the formula into, and then drag the formula down by using the little square in the bottom right hand corner of the cell you entered the formula into.
If you want to do it entirely in VBA, you can autofill using
Dim source As Range("A1")
Dim destination As Range("A1:A10")
source.AutoFill Destination:=destination
This will autofill from A1 to A10, as an example. You can also specify the autofill type with Type:
Dim source As Range("A1")
Dim destination As Range("A1:A10")
source.AutoFill Destination:=destination Type:=xlFillLinearTrend
The default type is xlFillDefault, which tries to find a pattern automatically and use the according fill type. Other types can be looked up here.

Loop and Add Range in a place holder

Hello,
First of all, thanks for everyone who's helped me with my previous concern. I have another loop issue though. What I'm trying to do is store a certain range on a place holder and use for Charts. My code loops through column A to check cells that contain Product/URL and if found, will offset to the next column and will store the range highlighted on a place holder.
What I was able to do so far is to just select the cell with content in-line with cell with Product/URL. Here's my code so far.
Dim ProdCell as Range
For Each ProdCell in [A:A].SpecialCells(xlCellTypeConstants)
If Not IsEmpty(Prodcell) and Prodcell.Cells.Value = [A1] Then
ProdCell.Offset(0,1).Cells.End(xlToRight).Select
End if
Next ProdCell
I believe that if I can find a way to highlight the range using VBA coding, I will be able to loop through it. Please help.

(Excel VBA) - Draw from cell text in a macro

I'm trying to build a small macro that allows the user to format multiple different documents at once.
I would like for the user to be able to enter into a particular cell within the document containing the macro a particular piece of text.
I then want for this piece of text to be able to be drawn upon in the macro while affecting a different document.
For instance, a code to add another column might say
Worksheets(1).Range("A1").EntireColumn.Insert
Instead of specifying the column (A), I would like it to draw on a value in the host document. For instance, the user types "G" into the particular cell, and then clicks a button to run the macro, and the macro will dynamically know to affect column G in all excel documents it targets based off of the value in the host document.
I hope this makes sense.
Any suggestions for the sort of functions I should be looking at to make this work?
"Any suggestions on the sort of functions I should be looking at?"
Here's a few...
To get the value which is entered...
If the cell will always be in the same address, say A1:
' Define a string variable and set it equal to value in A1
Dim cellText as String
cellText = ThisWorkbook.ActiveSheet.Range("A1").Value
or instead of using Range you can also use Cells which takes a row and column number.
cellText = ThisWorkbook.ActiveSheet.Cells(1, 1).Value
If the cell changes then you may need to look into the Find function to look for a label/heading next to the input cell. Then you can use it (easily with Cells) to reference the input...
Once you have this variable, you can do what you like with it.
To put this value into cell B3 in another (open) workbook named "MyWorkbook", and a sheet named "MySheet" you can do:
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range("B3").Value = cellText
To insert a column at cellText, do
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range(cellText & "1").EntireColumn.Insert
Notably here, the & concatonates the strings together, so if
cellText="B"
then
cellText & "1" = "B1"
Further to your comment about moving values between sheets, see my first example here, but always refer to the same workbook. If you find yourself repeatedly typing something like
ThisWorkbook.Sheets("MySheet").<other stuff>
then you can use the With shorthand.
With ThisWorkbook.Sheets("MySheet")
' Starting anything with a dot "." now assumes the with statement first
.Range("A1").Value = .Range("A2").Value
.Range("B1").Value = .Range("B2").Value
End With
Important to note is that this code has no data validation to check the cell's value before using it! Simply trying to insert a column based on a value which could be anything is sure to make the macro crash within its first real world use!

Using Search and Replace with VBA/Excel

Got an annoying Excel/VBA issue that I can't seem to get around - would appreciate any help.
I have a formula in a spreadsheet that says something along the lines of if the cell to its left =1, then the cell itself =on, and if not, ="off".
Is it possible to write some VBA search and replace code that turns "off" to "totally_off" when run?
At the moment it just seems to be editing the formula itself, while I really want it to delete everything in that cell and just replace it with the phrase "totally_off"
Thanks for your help.
The following code should work. Just replace the range B1:B10 with the range that the formulas you want to change are in. The procedure tests the value of the cell immediately to the left of the cells in the formula. If the value is zero, it replaces the formula with the "totally off".
Sub totally_off()
Dim rng As Range
Dim cell As Variant
Set rng = Range("B1:B10")
For Each cell In rng
If cell.Offset(0, -1).Value = 0 Then
cell.Value = "totally off"
End If
Next cell
End Sub
Here's a non-VBA, non-search and replace alternative.
Set up a filter on the formula column with Sort and Filter / Filter on the Home ribbon.
Select "off" from the drop-down menu on the column.
Type "totally off" in the first cell of the filtered column and copy it down to the bottom of the column.
Then remove the filter. The formulas evaluating to "on" will remain intact.
No need for VBA - simply use an AutoFilter:
Select the column with the on/off formula
Apply an AutoFilter (Ctrl-Shift-L
Filter for off
Again, select all values
Simply type in your replacement value totally_offinto the formula bar - but press Ctrl-Enter
Done!

Excel VBA - Interpret "N/A" Values

I am traversing a spreadsheet which contains a column of prices, in the form of double types. I am trying to locate a missing value which is shown on the spreadsheet as "n/a", but it is not letting me interpret this as a string type.
The cell containing "n/a" seems to be an integer type; how can I read this?
If all you want to do is to check for the error value then:
Application.WorksheetFunction.IsNA(rngToCheck.Value)
where rngToCheck is the cell which you want to check for the #N/A error value
(There's a list of the worksheet functions which can be called from Excel VBA here)
You could also examine rngToCheck.Text as this will contain the string "#N/A"
If instead, you want to read the formula in the cell which generated the #N/A then rngToCheck.Formula would do that
A cell containing #N/A is retrieved by VBA as a variant containing an error code
In general its usually best to assign Excel cells to Variants because a cell can contain a number(double), logical, string or error and you cannot tell in advance what the cell wil contain.
You can prepare the spreadsheet you like to check as described below and evaluate the special cells containing the IS Functions, it is easy to check them for True or False in VBA. Alternatively, you can write your own VBA function as shown below.
There are Excel functions which check cells for special values, for example:
=ISNA(C1)
(assumed that C1 is the cell to check). This will return True if the cell is #N/A, otherwise False.
If you want to show whether a range of cells (say "C1:C17") has any cell containing #N/A or not, it might look sensible to use:
=if(ISNA(C1:C17); "There are #N/A's in one of the cells"; "")
Sadly, this is not the case, it will not work as expected. You can only evaluate a single cell.
However, you can do it indirectly using:
=if(COUNTIF(E1:E17;TRUE)>0; "There are #N/A's in one of the cells"; "")
assuming that each of the cells E1 through E17 contains the ISNA formulas for each cell to check:
=ISNA(C1)
=ISNA(C2)
...
=ISNA(C17)
You can hide column E by right-clicking on the column and selecting Hide in Excel's context menu so the user of your spreadsheet cannot see this column. They can still be accessed and evaluated, even if they are hidden.
In VBA you can pass a range object as RANGE parameter and evaluate the values individually by using a FOR loop:
Public Function checkCells(Rg As Range) As Boolean
Dim result As Boolean
result = False
For Each r In Rg
If Application.WorksheetFunction.IsNA(r) Then
result = True
Exit For
End If
Next
checkCells = result
End Function
This function uses the IsNA() function internally. It must be placed inside a module, and can then be used inside a spreadsheet like:
=checkCells(A1:E5)
It returns True, if any cell is #N/A, otherwise False. You must save the workbook as macro-enabled workbook (extension XLSM), and ensure that macros are not disabled.
Excel provides more functions like the above:
ISERROR(), ISERR(), ISBLANK(), ISEVEN(), ISODD(), ISLOGICAL(),
ISNONTEXT(), ISNUMBER(), ISREF(), ISTEXT(), ISPMT()
For example, ISERR() checks for all cell errors except #N/A and is useful to detect calculation errors.
All of these functions are described in the built in help of Excel (press F1 and then enter "IS Functions" as search text for an explanation). Some of them can be used inside VBA, some can only be used as a cell macro function.