Set any range with userform - vba

I am currently looking for a way to assign a range via UserForm. I've often encountered the example with the RefEdit, which unfortunately does not fit 100% to my problem.
Is there a way where the enduser can assigns a range with a textbox? The User should be asked in which column in his sheet the relevant numerical values are and on that basis, the macro should adjust the range.
For example:
The user types the range is in column H and there for the macro adjust to:
ws.Range("H2: H" & lastrow)

ws.Range(Var & "2:" & Var & lastrow)

Related

Syntax error for INDEX formula using Macro

I'm getting a syntax error when I try to insert a formula in a cell using Macro. I can't seem to figure out what am I doing wrong? The formula works fine when I manually enter it. Here's my code:
ws3.Range("F2:F" & lastRow3).Formula = "=INDEX($L$1:INDEX(L:L,MATCH("ZZZ",D:D)),AGGREGATE(15,6,ROW($K$1:INDEX(K:K,MATCH("ZZZ",D:D)))/($K$1:INDEX(K:K,MATCH("ZZZ",D:D))=D2),COUNTIF($D$1:$D2,D2)))"
ws3 is the worksheet, and lastRow3 is just to autofill the contents by comparing to a column to the left. Any ideas why this is giving an error?
FYI: This formula is finding values in one column from another column and giving the adjacent entries.
When filling a full range it is best to use R1C1 format.
Also with using vba to set the last row there is no reason for all the INDEX(L:L,MATCH("ZZZ",D:D)) to find the last row, since the code itself can set it directly.
Use this:
ws3.Range("F2:F" & lastRow3).FormulaR1C1 = _
"=INDEX(R1C12:R" & lastrow & "C12,AGGREGATE(15,6,ROW(R1C11:R" & lastrow & "C11)/(R1C11:R" & lastrow & "C11=RC[-2]),COUNTIF(R1C4:RC4,RC[-2])))"

Excel use cell value as range in VBA

I have an excel file. There is a changable row quantity for column A for every time and that's why I need to make dynamic formula. For example;
I want to write "=LEN(B1)" formula on B1. And when make double click on right down corner of the cell, it's going to the end of until when column A values ends. That's why, before all this process, I wrote "=COUNT(A:A)" on cell C1.
In my VBA, I want to write;
Dim TEMP As String
TEMP = Range("C1").Value
Range("B1").Select
ActiveCell.FormulaR1C1="=+LEN(RC[-1])"
Selection.AutoFill Destination:=Range("B1:TEMP")
But there is something wrong in this process. As a result, I just want to use a cell value in my VBA as a range or string or number.
Thanks for your support.
Two notes:
It's best practice to always qualify your objects (workbooks, worksheets, ranges, etc.) beforehand
When you use R1C1 notation, you can just write the formula directly to the range (with no need for AutoFill or FillDown)
Try this:
Dim ws as Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") 'edit for your sheet name
Dim lRow as Long
lRow = ws.Range("A" & ws.Rows.count).End(xlup).Row
ws.Range("B1:B" & lRow).FormulaR1C1 = "=Len(RC[-1])"
And just as a side note worth mentioning the way you wrote Range("B1:TEMP") is not proper syntax. Correct syntax would be Range("B1:B" & TEMP), which, of course, would only work if TEMP was indeed a numerical value :)

Declaring last row references in Excel formulas through VBA

In an attempt to take one of my rudimentary programs, and develop it more I am in need of help referencing last row references in Excel formulas as well as dragging formulas down consistently to the last row of a document.
To elaborate I am attempting to reference the last row in an ever expanding mapping table in my vlookup formula. The reason I need this is because as this mapping table expands when I am no longer coding this program, I need my vlookup formula which will be generated every time I run the program to adapt to the ever changing size.
Also my more pressing issue is in regard to taking that vlookup formula and being able to drag it down to the last row of a worksheet. The worksheet will be static and the last row will range anywhere from 70,000 rows to 90,000 rows. I am trying to avoid loops in this scenario as this will already be a very demanding formula and I would hate to loop through each row.
Currently my rudimentary code looks like this (this was built as a proof of concept, I understand the current method isn't the most ingenious but it served its initial purpose).
Ath.Cells(1, x) = "Business"
Ath.Cells(2, x).Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R2C4:R264C5,2,0),VLOOKUP(LEFT(RC[1],2),Mapping!R1C3:R264C5,3,0))"
Ath.Range("d2").Copy
Range("d2:d90000").Select
ActiveSheet.Paste
Calculate
I namely want to change this
Ath.Range("d2").Copy
Range("d2:d90000").Select
ActiveSheet.Paste
and
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R2C4:R264C5,2,0),VLOOKUP(LEFT(RC[1],2),Mapping!R1C3:R264C5,3,0))"
Perhaps these?
Ath.Range("d2").Copy
Range("d2:d" & Range("D" & Rows.Count).End(xlUp).Row).Paste
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R2C4:R" & Sheets("Mapping").Range(ActiveCell.Offset(Rows.Count, -1)).End(xlUp).Row & "C5,2,0),VLOOKUP(LEFT(RC[1],2),Mapping!R1C3:R" & Sheets("Mapping").Range(ActiveCell.Offset(Rows.Count, -1)).End(xlUp).Row & "C5,3,0))"
Combining Dans answer with work of my own I have developed a solution.
Sub Formulas()
Dim Map As Worksheet
Dim Ath As Worksheet
Dim last As Long
Set Ath = Sheets("Athena IBT TEST")
Set Map = Sheets("Mapping")
last = Map.Cells(Rows.Count, "D").End(xlUp).Row
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R1C1:R" & last & "C4,4,0),IFERROR(VLOOKUP(LEFT(RC[1],3),Mapping!R1C2:R" & last & "C4,3,0),VLOOKUP(LEFT(RC[1],3),Mapping!R1C3:R" & last & "C4,2,0)))"
End Sub

Calling an existing worksheet with vba by using its code name in excel

I am trying to set the formula of a cell to an if formula that uses data from an already existing sheet within the workbook. However whenever trying to reference the sheet i get a file dialog box that opens looking for the path for the sheet. Below you will find my code which loops through all existing sheets in the workbook and compares it to a sheet name when it finds a match it stores the sheet code name for the current and previous weeks. Once it has these I have an if statement that tries to access these sheets and compare values. It is at this point that I get the file dialog box. Any thoughts or suggestions would be greatly appreciated. Thank you. Sorry for formatting issues I will correct as soon as possible.
sheetName = CStr(Year(Now)) & " eDR FW" & CStr(Format(Date, "ww")) & "_2"
lastWeekName = CStr(Year(Now)) & " eDR FW" & CStr(Format(Date, "ww") - 1) & "_2"
For Each ws In ActiveWorkbook.Worksheets
If ws.Name = sheetName Then
sheetName = ws.CodeName
ElseIf ws.Name = lastWeekName Then
lastWeekName = ws.CodeName
End If
Next
rowRange = colLetter & "2:" & colLetter & CStr(sheetRowCount)
lineofBalance = "=IFERROR(IF(INDEX('" & lastWeekName & "'!$A$2:$W$10000,MATCH(A2,'" & sheetName & "'!$A$2:$A$10000,0),6)=F2,F2,CONCATENATE(""Updated: ""&F2)),CONCATENATE(""New: ""&F2))"
All you need to do to make this work is change both ws.Codename to ws.Name.
The .Codename property only contains the first name of the sheet when it was originally created (which is most likely something like "Sheet32") and not the current name of the worksheet. It CAN be changed but most likely will remain the same unless you REALLY intend to change it. The formula with the erroneous worksheet name then opens the dialog box to try to find a reference for that particular worksheet.
Excel's formulas are designed to work with the current worksheet name and not it's codename. The only useful way I can see of using the .Codename, is if you wanna make sure to always use a particular worksheet (within VBA) even if the name of the worksheet was changed at some point (by yourself or a user).

Summing cells from another sheet using offset

I'm trying to get this code to work for summing cells:
Worksheets("Sheet2").Range("C3").Offset(i, j).Formula = "=Sum("
&Worksheets("Sheet1").Range("A3").Offset(2*i,j).Address & ":" &
Worksheets("Sheet1").Range("A7").Offset(2*i,j).Address & ")"
It keeps giving me the right cells but from the wrong sheet. So for the first iteration I get sum(A3:A7) in cell C3 of Sheet2 but the A3:A7 stays referenced to Sheet2 not Sheet1.
Thanks!
You need to specify the name of the sheet in the formula too. Your code will work if you write it like this:
Worksheets("Sheet2").Range("C3").Offset(i, j).Formula = "=Sum(Sheet1!" & _
Worksheets("Sheet1").Range("A3").Offset(2 * i, j).Address & ":" & _
Worksheets("Sheet1").Range("A7").Offset(2 * i, j).Address & ")"
Try this code - it uses the External:=True parameter of .Addressto retrieve the full address. While this also includes the workbook name, Excel will remove this automatically so you end up with Sheet1!A3. Also note that I used the range A3:A7 as source as .Address can handle multi-cell ranges and you don't need to take care of it manually:
Sheets("Sheet2").Range("C3").Offset(i, j).Formula = "=SUM(" & _
Sheets("Sheet1").Range("A3:A7").Offset(2 * i, j).Address(External:=True) & ")"
Be aware that hard coding references such as A3 can lead to bugs in the long run, as the user (or even the developer at some stage) might modify the sheet structure. It is best practice to use named ranges, i.e. create a named range for each cell/range you refer to and then access it in VBA with SheetX.Range("rngStartCell") or similar!