Variable Named Ranges in Excel - vba

I have a table in Excel formatted as follows:
Date Asset Return
1/3/2005 0.003582399
1/4/2005 -0.01908258
1/5/2005 0.002080625
1/6/2005 0.005699497
1/7/2005 -0.008040505
1/10/2005 -0.00339116
1/11/2005 -0.009715187
1/12/2005 0.002371855
1/13/2005 -0.00580783
1/14/2005 0.001058481
1/18/2005 0.015483842
1/19/2005 -0.014690715
1/20/2005 -0.015714799
1/21/2005 -0.010796326
I need a named range to reference each column. The workbook is a template, so the named range won't always cover the same number of rows depending on the data. I want to set it so that the named range "Date" and the named range "Asset Return" are automatically sized to cover the entire column from the first value until the last, without going past the last value in the column.
It will always start at cell B8, but might end at a different row depending on the size of the data.
How can I set a dynamic named range to accomplish this?

This named range formula will do it:
=Sheet1!$B$8:INDEX(Sheet1!$B:$B,COUNTA(Sheet1!$B:$B)+8)
Remember to add the sheet name as the named range will operate on the active sheet otherwise.
The formula starts takes B8 as it's starting point: Sheet1!$B$8
It then counts how many cells are not blank in column B: COUNTA(Sheet1!$B:$B)
It adds 8 to the count (assuming your first rows are blank).
It then uses INDEX and the COUNTA to reference the last cell.
https://support.office.com/en-gb/article/INDEX-function-a5dcf0dd-996d-40a4-a822-b56b061328bd
https://support.office.com/en-gb/article/COUNTA-function-7dc98875-d5c1-46f1-9a82-53f3219e2509

Try this VBA code
Sub test()
application.DisplayAlerts = false
Range("B8").currentregion.createnames _
top:true, right:=false, left:=false, bottom:=false
application.DisplayAlerts = true
end sub

Related

copy selected row cell entries to other sheet

I'm trying to provide the capability to select either a row or column in a row and copy certain cells off the row into a different sheet.
For example...I have a list of renters (rows) each with the amount they owe and the amount collected on one sheet and the other sheet is a receipt. I'd like to enter the rent collected and have the receipt sheet updated automatically with the other sheets rows/individuals name and amount collected.
Is there a VB function to identify the active row?
If I can get that working the next thing would be adding/incrementing the invoice number.
You can use a combination of UsedRange and the Rows() property to get your active row.
While UsedRange is not necessarily required, it would only select the used cells in that row as opposed to selecting the entire row of the workbook, which is very likely unneeded.
You can use this function:
Function rngActiveRow() As Range
Dim ws As Worksheet
Set ws = ActiveCell.Parent
Set rngActiveRow = ws.UsedRange.Rows(ActiveCell.Row)
End Function
If you wanted to test it, you can try calling this function in a test sub to see it work:
Sub test()
rngActiveRow.Select
End Sub

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

Copy rows based on cell value and paste on a new sheet

Check This
I need a help. I want to copy whole cell from A sheet name "Components" only if value in Column C is > 0 to a new Sheet name "Load list"
Can someone please give me the macro code for this?
on your new sheet you can add this condition the cell or range of cells:
=IF(Components!C5>0,Components!A5)
where C5 has thevalue to compare, and A5 has the value copy if the condition happens.
Right in my swing!
The formula given by #sweetkaos will work fine, in case you want to replicate the data as it is with blanks where data is not found.
I will imagine a slightly more complicated situation. I am assuming you want just one line in the next format as is shown in your image.
Also conveniently assuming the following:
a. both sheets have fixed start points for the lists
b. 2 column lists - to be copied and pasted, with second column having value
c. Continuous, without break source list
d. basic knowledge of vba, so you can restructure the code
Here is the code. Do try to understand it line by line. Happy Excelling!
Sub populateLoadList()
'declaring range type variables
Dim rngStartFirstList As Range, rngStartLoadList As Range
'setting values to the range variables
'you must change the names of the sheets and A1 to the correct starts of your two lists
Set rngStartFirstList = Worksheets("Name_of_your_fist_sheet").Range("A1")
Set rngStartLoadList = Worksheets("Name_of_your_second_sheet").Range("A1")
Do While rngStartFirstList.Value <> ""
If rngStartFirstList.Offset(1, 0).Value < 0 Then
Range(rngStartFirstList, rngStartFirstList.Offset(0, 1)).Copy
rngStartLoadList.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Set rngStartLoadList = rngStartLoadList.Offset(1, 0)
End If
Set rngStartFirstList = rngStartFirstList.Offset(1, 0)
Loop
End Sub
Basically what i want is ... if Value on C is >0 i want whole column 10 copied to that new sheet .... not only that cell

Best way to return data from multiple columns into one row?

I have a sheet with just order numbers and another with order numbers and all of the data associated with those order numbers. I want to match the order numbers and transfer all of the available data into the other sheet. I've been trying to use loops and VLOOKUP but I'm having problems (plus I have 116 columns I want to transfer data from so my vlookup expression doesn't look very nice). Any advice would be appreciated!
this is what I have so far and I'm getting an object error.
I don't think it's the right way to go about it in general though.
Dim LookUpRange As Range
Dim row As Range
Set LookUpRange = Worksheets("batches").Range("B4:B1384")
Set row = Worksheets("batches").Range("C:DL")
For Each row In LookUpRange
row.Select
Selection.FormulaArray ="=VLOOKUP(RC[-1],OrderLvl!RC[-1]:R[1380]C[113],{2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,207,108,109,110,111,112,113,114,115},FALSE)"
Next row
End Sub
Please consider this VBA script to resolve your inquiry:
Sub LookupOuput()
Dim OrderNumberColumn As Range
Set OrderNumberColumn = Worksheets("batches").Range("B2:B1384")
Dim LookUpRange As Range
Set LookUpRange = Worksheets("OrderLvl").Range("C:DL")
Dim cell As Range
Dim FindResult As Range
For Each cell In OrderNumberColumn
If Not cell.Value2 = Empty Then
Set FindResult = LookUpRange.Find(what:=cell.Value2)
If Not FindResult Is Nothing Then
cell.Range("A1:DJ1").Value2 = LookUpRange.Rows(FindResult.row).Value2
End If
End If
Next cell
End Sub
Basically searches for each Order Number in the first sheet on the second sheet. This outputs (if search term exists) the cell that that string is found which we later refer to its row number to output the whole row to the first sheet. Cheers,
A regular VLOOKUP may be able to give you what you need, if you use a small trick...
Insert a row above the data table, and put sequential numbers in
each cell of that row. (ie, A1 = 1, B1 = 2, C1 = 3, etc...)
Do the same thing on your blank table.
Assuming that your first order number is in cell A2, put the following formula into B2: =VLOOKUP($A2,[other sheet name]!$A$1:$DZ$5000,B$1,0)
Drag this formula across all 116 columns, then down all however many rows you've got.
You'll need to adjust the ranges, obviously, but make sure that your lookup array starts in column A. (or alternatively, that your numbers start in the same column as the first column in your array.) Adding the numbers along the top allows you to change what column of the array you're referencing, just by dragging the cell formula.

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.