Blank cells in matrix take on average of surrounding cells in Excel - vba

I have a matrix of numbers in excel that contains several blank cells. The numbers correspond to the clay level in the ground, as indicated by a borehole in that position. I am using the cells as a grid to represent a map. I want to replace the blank cells with an average of all of the cells which surround it. How do I do this? I keep getting circular reference errors when I try to do it.

1) Use a proxy range: Create a duplicate range and have that refer to the original. The named range here is F5:H6
For above the range on the left (F5:H6) is called namedRange and the blank cell in the duplicate range on the right uses Average(namedRange) to populate the value.
To add a named range , select your range and then add the name via the name manager .
OR
2) Use VBA
With VBA using the same named range (code in a standard module - replace activesheet with your sheetname) :
Option Explicit
Sub test()
With ActiveSheet.Range("namedRange")
.SpecialCells(xlCellTypeBlanks) = Application.WorksheetFunction.Average(.Value)
End With
End Sub

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.

Macro to find and delete column based on cell value

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.

Excel VBA Changing text inside shapes based off a range of cells

I have made a large diagram of made by shapes with numbers stored inside as text and need to change the "old" numbers to a "new" range of numbers. On each of the 20 sheets there are circles, Rectangles, Left Arrows and Right Arrows. The old range of numbers are stored on a separate spreadsheet in the Column "A" and need to be changed to the numbers listed in Column "B" (as in A1 to B1).
What would a VBA method to change the old text inside the Shapes to the new correct text based off of a new range of numbers? Is it possible to write a script that changes the values in the entire WorkBook?
My incorrect way of thinking is to:
1. Search inside the diagram to find the various shapes.
2. Get the text inside each shape.
3. Compare the text with the spreadsheet with the old numbers.
4. Insert the new number.
5. Move onto the next shape.
Put a value in A1 and say we already have a Shape:
Running this:
Sub LinkCellToShape()
Dim sh As Shape
Set sh = ActiveSheet.Shapes(1)
sh.DrawingObject.Formula = "=A1"
End Sub
will link the text in the shape to the value in the cell. You could also use:
sh.OLEFormat.Object.formula = "=A1"

Keeping column formulas in a table header

Is it possible to have the formulas that I need applied on columns be saved or applied to a column header or some kind of metadata so that as and when I add new rows to my Excel table the Formulas get applied to the columns?
Scenarion:
I am creating a template Table, which will have no rows at first.
On a separate sheet (or same sheet for that matter) once the user selects the number of rows to be generated in the table, I dynamically add rows to the table using VBA.
The idea is I may not have any rows in the table at beginning OR user may have deleted rows manually.
When I programmatically add new rows, I want the Formulas applied on the cells as well. Most of the formulas I am using are either of the three types:
Structured table reference, Excel functions like SUM, AVERAGE etc and custom function names.
Updated:
Here is what I have tried:
1> tried applying the formula to the header itself.
Result: The header it self changes with #REF! error. I think the behavior is correct. So it's a no-go option.
2> Tried creating one row and apply the formula to the row. That works, but the problem is, I do not want a dummy row to begin with.
3> Using VBA code to add row to the table using
ActiveWorkbook.Worksheets("Sheet3").ListObjects("Table2").ListRows.Add AlwaysInsert:=True
inside a for loop.
The new rows retain the visual style sheets, but does not seem to retain the formulas. Just blank cells.
Could the fomrmulas be in header cell commnets?
And then with VBA add the formula for the current row:
Sub test()
Dim headerCells As Range
Set headerCells = Range("B2:E2")
OnNewRow 3, headerCells
End Sub
Sub OnNewRow(newRow As Integer, headerCells As Range)
Dim headerCell As Range, targetCell As Range, formulaFromComment As String
For Each headerCell In headerCells
formulaFromComment = GetFormulaFromComment(headerCell)
If (formulaFromComment = "") Then _
GoTo NextHeaderCell
Set targetCell = Intersect(headerCells.Worksheet.Rows(newRow), _
headerCell.EntireColumn)
AddFormula newRow, targetCell, formulaFromComment
NextHeaderCell:
Next
End Sub
Sub AddFormula( _
newRow As Integer, _
targetCell As Range, _
formula As String)
formula = Replace(formula, "{ROW}", newRow)
targetCell.formula = formula
End Sub
Function GetFormulaFromComment(headerCells As Range) As String
' TODO
GetFormulaFromComment = "=SUM($C${ROW}:$E${ROW})"
End Function
Just use tables.
If you highlight cells and choose Insert Table from the ribbon, it doesn't just give you formatting and filters. It also, if you build them the right way, stores column formulas once per column instead of once per cell. Also, the formulas are more readable!
For formulas, you can't use cell addresses if you want it to be a single column formula unless they are absolute. (E.g. $A$1, not A1.) Instead, you use [ColumnTitle] for the entire column (where "ColumnTitle" is the actual title of that column) and [#ColumnTitle] for the column value in the same row. So if "Cost" was the title of column B, "RunningTotal" was the title of column C and your formula for C6 was therefore =B6+C5, you'd instead use a formula of =[#Cost]+OFFSET([#RunningTotal],-1,0)] which is longer but much easier to read/maintain/debug, and if you change a column title then the formulas change too! No VBA required. Given this, plus being able change columns for the entire columns at once, plus being able to refer to other columns in other tables without worrying about cell addresses (e.g. MAX(Table1[Cost])), plus being able to style the tables so easily, plus the integration with Power-Query, and VBA support. (See learn.microsoft.com.) Whether VBA or otherwise, add a row to your table and the columns with a single column formulas will automatically carry over into the new row.
Not sure about Table templates or VBA but perhaps there is another option by using =ARRAYFORMULA()
For example, say you had a header row and 3 columns and wanted your last column to be the product of the first two. In cell C2 you could enter the following:
=ARRAYFORMULA(A2:A*B2:B)
This has three benefits:
Skips the first row completely
Effectively applies the formula to every row which is useful if you later decide to insert a row (your question)
Only one location to modify the formula for every single row
Although, it may not be immediately obvious where how/where the cells are being calculated. (hint: ctrl+~ may help)

How to find Cell that contains a Range in Word VBA

In Word VBA I have a reference to a Range that is contained withing a table cell.
How can I get a reference to the containing cell (the innermost cell if there are nested tables)?
What I'm trying to achieve is to find the cell containing my range, then move to the next adjacent cell.
This worked for me:
Debug.Print rng.Cells(1).Next.Range.Text