How to name dynamic column in excel using VBA - excel

I have been learning VBA for a while but there is one issue that I have been facing that I was not able to figure it out until know.
I want to be able to name a column using VBA, so I can use it later it as a reference column (using INDEX function) in other cells/columns.
I know to how to name a column that is fixed. But that is not what I am looking for.
Example of my issue:
This month I am naming column D as TotalAmount.
The VBA code can be:
ActiveWorkbook.Names.Add Name:="TotalAmount", RefersToR1C1:="=Sheet1!C4"
I will be referring to that column in other cells using the INDEX function.
However, next month I will be adding a new column (let's say previous month sales) just before Column D. So the new column that I want to name as TotalAmount the next month will be column E as opposed to D.
I know that the Column naming should not change when adding a new column and Column E will automatically become the TotalAmount column. However, I cannot rely on it because the excel sheet is accessed by different people and everyone is doing his own calculations.
So I tried this as well (I am sure it is stupid but hey I am still a noob) but it did not work :(
Sub Macro4()
Range("D1").Select
'(I can select the desired cell each month using the search function)
Dim i As Integer
i = ActiveCell.Column
ActiveWorkbook.Names.Add Name:="TotalAmount", RefersToR1C1:="=Sheet1!Ci"
End sub
So I will be very grateful if anyone could help me or guide me on this subject.

'i' is a variable so you cannot use that in quotes. In quotes, its just 'i' and has no value. try ActiveWorkbook.Names.Add Name:="TotalAmount", RefersToR1C1:="=Sheet1!C" & i
Not sure if this will resolve your problem though

You can get VBA to find the cell for you:
Sub SetNamedRange()
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:Z1").Find("TotalAmount")
ThisWorkbook.Names.Add Name:="TotalAmount", RefersToR1C1:=rng
End Sub
The code searches A1:Z1 for the text "Total Amount" and sets the named range to that cell

Related

How does one write a VBA macro which generates a SUMIFS table using a user selected column as an input in the formula?

Not sure if this is even possible but I'm just curious. I know you can make VBA automatically populate a formula in certain cells in Excel, and also that you can insert columns and such next to a user selected cell. Is it possible however to write a code in which the user selects a column that contains data 1 (dates for example), and then selects a column with data 2 (names for example) and a final column with data 3 (dollar values). Then the code would run on a predefined range (a table that has names as row headers and dates as column headers) and populate a SUMIFS formula into all the cells- with the user selected columns as the criteria range and the defined name rows and date columns as the criteria.
If someone can point me on the right direction I'd greatly appreciate this. I'm struggling to figure out how to structure this macro so that a user input variable can be used inside the SUMIFS formula, changing the criteria range in the formula based on what the user selects. Let me know if this even seems possible in VBA.
I've tried creating macros which automatically populate a formula like SUMIF into a range, but the problem is that the formula has to be fixed in the VBA code with certain constants. What I'm looking for would have to be variable, and the parameters of the formula be taken from user inputs.
Appreciate any help or knowledge on this topic. Thanks.
In code I used before I needed to be able to select a column and then use it later on,
On Error Resume Next
Set columnStart = Application.InputBox("Select the column of the first key", Default:=Selection.Address(0, 0), Type:=8)
On Error GoTo 0
If columnStart Is Nothing Then
MsgBox "Cancelled."
GoTo EndSkip
End If
Set wbV = columnStart.Parent.Parent
columnAddress = columnStart.Address
columnNr = columnStart.Column
wbV.Activate
Set ws = wbV.ActiveSheet
and use it later on in a VLOOKUP
Range("N2:N" & Lastrow).FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-1],'[" & wbV.Name & "]" & ws.Name & "'!C" & columnNr & ",1,0), ""0000NO"")"
This should help you how to use them as variables in a formula.
I believe my info came partly from here User input box to pick column to perform action

Emtpy a Cell If another Cell becomes empty

Good day dear community,
I currently have a problem with VBA/Excel that I can't find a solution to. What I want to achieve is not complicated, but I can't find a way.
Let's assume we have two columns. In any row of one column A the User enter a value and then I start a macro. This macro executes certain instructions. Among other things, this macro ensures that if a cell in column A has a value, then the value "Yes" is entered in the same row in column B. Now my problem: As soon as the user deletes the cell value in column A, the value "Yes" in column B should also be deleted. At first glance you might think that i can use this confdition:
=IF(A1="";"";yes)
The problem is that as soon as the user has entered a value in the cell, "yes" is immediately written in the cell, but this is not desired. Because this task should be taken over by the macro.
As a small side note: I have simplified my problem. Due to the structure of my project, only the macro is allowed to write "yes".
Thanks.
Evaluate Excel Formula in VBA
In your code, you will define the occupied range in column A, and apply the second line appropriately.
Option Explicit
Sub checkColumnRange()
' Some code
' Define the column range...
' e.g.:
Dim rg As Range: Set rg = Range("A1:A10")
rg.Offset(, 1).Value = Evaluate("IF(" & rg.Address(0, 0) _
& "<>"""",""Yes"","""")")
' Some code
End Sub

How to use VLOOKUP in Excel VBA to find matching cells

I am just starting out with Excel VBA and to be honest I am not that skilled in using normal Excel either.
I've got one sheet that has unique codes in column C, I also have another sheet that has unique codes in column A (except first rows as they've got column labels).
In case this unique code from sheet 1 is also found in the column in sheet 2, I want column J in the sheet1 to have that code value, otherwise, if it cannot be found, I want it to have #N/A.
Normally in Excel I would do this by selecting J2 and entering following function:
=VLOOKUP(C2,Sheet2!A:A,1,False)
Then I'd just double click the corner of the cell to populate all rows.
How do I do it in VBA? I wrote this code hoping it would do something:
Worksheets("Sheet1").Activate
ActiveSheet.Range("J:J").Value = Application.VLookup(C2,Worksheets("Sheet2").Range("A:A"),1,False)
However, this does not work. I just get #N/A for all cells in the J column. Any suggestions what I can do?
The following code will give you what you want. Note that you would only want to put the formula into rows where values actually exist in column C on sheet1.
Option Explicit
Sub InsertVlookup()
Dim LastRow As Long
LastRow = Sheet1.Cells(Rows.Count, 3).End(xlUp).Row
With Sheet1.Range("J2:J" & LastRow)
.FormulaR1C1 = "=VLOOKUP(RC[-7],Sheet2!C[-9],1,FALSE)"
.Value = .Value
End With
End Sub

Excel: How to refer to entire column in a formula by column title?

I want to write a formula like =SUM(tab2!A:A) but instead use the column title of A which is say "count". How can I modify this to look more like: =SUM(tab2!"count")?
The reason I want to do this is because I copy and paste a spreadsheet from another source in tab2 and the column referring to "count" may be in a different column. I want the formula to give me the correct calculation as soon as I paste the new spreadsheet by automatically finding the column to sum up by title name.
I must be missing something because this seems like a very basic question and I can't find the answer anywhere...
Thanks for your help!
I like the idea of naming ranges proposed by #Doug, but if the issue is that you are dumping your data in [and you don't know in advance which column is going to be where] and would need to rename your range every time, there are other options - I suggest using OFFSET. OFFSET allows you to dynamically create a range, starting at a particular point and moving down/up / right/left for as many rows and columns as you determine.
In your case, you will need to combine that with a method for searching the columns to see which one says "Count". I am assuming that your column headings are always in row 1. If they aren't [or if they aren't always in row 2, or any row you know in advance]... you can get around that but then I'd recommend you try to make your data more uniform instead of creating unnecessary Excel workarounds.
In total your formula would look like this:
=SUM(OFFSET(A1,,MATCH("Count",1:1,0)-1,ROWS(A:A),1))
What this does is first determine which column the word "Count" is found in, in row 1. Then it subtracts 1 from that number - this now equals the number of columns to the right that it is, from column A. It uses offset to create a reference to that column, for all rows, and sums those rows together.
Check out the name manager for naming ranges :)
You didn't say whether you would consider a macro solution. If so, this may work.
If the sheet you are pasting into is Sheet2 and the sheet you want the result in is Sheet1, then this macro, if placed in the Worksheet_Activate event of Sheet1 will give you the result as soon as you click on the Sheet1 tab afetr pasting your data into Sheet2:
Private Sub Worksheet_Activate()
Dim r As Range
Dim rCol As Range
Dim rFound As Range
Dim ws As Worksheet
Dim lTotal As Long
Set ws = Sheet2
Set r = ws.Cells
Set rFound = r.Find("count")
If Not rFound Is Nothing Then
Set rCol = rFound.EntireColumn
lTotal = Application.WorksheetFunction.Sum(rCol)
End If
Cells(1, 1) = lTotal
End Sub
It does assume there is only one cell with the word "count" in it on Sheet2.

Excel VBA: changing hard coded column to dynamic range to autofill to last row

Hello from an unexperienced vba user.. I'm having trouble with the code for autofill to the last row when trying to use named ranges for the column. Everything seems to work fine when I use a hard coding for the column, in this case Column CW, and what I need is to replace this column CW with a named range so that the macro will still work when adding or deleting columns in the worksheet.
I used the following named ranges:
First_Date: This is the header cell of one of the columns (in this case AP5)
Second_Row: This is the range of columns I want to copy the formulas from (AP7:CW7)
Second_Cell: The cell where I want to start to autofill (AP7)
Last_Column: This is column CW that I want to use in the code. Autofill would be up to this column and down to the last row.
After searching in different threads, I came up with the following code that seems to work fine. How can I change column CW to a named range? Or do I need to change the code?
Dim Lr As Integer
Lr = Range("First_Date").End(xlDown).Row 'Searching last row
Rows(Lr).Insert Shift:=xlDown 'Inserting new row
Range("Second_Row").AutoFill Destination:=Range(Range("Second_Cell"), Range("CW" & Lr))
Can anyone assist me here please?
This will get the job done :-)
Sub RangerFiller()
'The Cell that holds the formula B1
OriginalFormula = Cells(1, 2).Formula
'copies formula down to the last column next to B but use can use another column as
'a counting column....the column that hold the last value
Range("B2:B" & Cells(Rows.Count, "A").End(xlUp).Row).Formula = OriginalFormula
End Sub
Someone gave me the solution:
Change
Range("CW" & Lr)
To
Cells(Lr, Range("Last_Column").Column)
I faced a similar problem because I don't want to hard code the cell reference. I found this solution below to be useful, by using "& ______ &" to replace the cell number that can be calculated using input box or formula.
Eg.
cell1 = last row of column A
Range("CW " & cell1 &" :CW & Lr),
where cell1 = any number that can be added via input box/formula.
Hope this helps!

Resources