Use value from one cell to define "coordinates" of another cell - excel

I want to use the value of one cell, e.g. 3 to specifiy the coordinates of another cell.
This is what I tried:
Wert = Range("E22").Value
Sheets("Tabelle2").Range("A1:BWert").Copy

When cell coordinates are calculated you will find it more expedient to specify cells as `Cells([Row], [Column]) and define a range by its first and last cell. When you employ this syntax your task would be solved like this:-
With Sheets("Tabelle2")
.Range(.Cells(1, 1), .Cells(Wert, 2)).Copy
End With
The variation below is equivalent and perhaps easier to read for a beginner. However it is logically inconsistent because column letters can't be calculated.
With Sheets("Tabelle2")
.Range(.Cells(1, "A), .Cells(Wert, "B")).Copy
End With

I tried it in my actual code and it did copy it however it pasted it from A1 and A1 to like J 1 and J2. heres my entire code: It was supposed to copy the range A1:B10 from Table2 to A1:B10 in Table3.
How could this be done?
Option Explicit
Sub Kopieren()
Dim Wert As Integer
Wert = Range("E22").Value
Sheets("Tabelle2").Range("A1:B" & Wert).Copy
Sheets("Tabelle3").Range("A1:B" & Wert).PasteSpecial xlPasteValues, Transpose:=True
End Sub```

Related

How to use a user defined range in a formula in vba

I am trying to define a range starting at B2 (constant) to the last cell with data which will change month to month. I want to take the same range length and define another range for column A which will also start at A2 (constant) but will extend only down as far as column B goes. I'm trying to identify them as range and use the dimmed range in a formula in vba but it doesn't like it...any ideas?
Dim Data As range
Dim Time As range
range("b2").Select
'Select Range
Set Data = range("B2", range("B2").End(xlDown))
Set Time("A2", range("A2").End(xlDown))
ActiveCell.Offset(1, 1).Select
ActiveCell.FormulaR1C1 = _
"=FORECAST.ETS([#Timeline],.address(data),.address(time):R[-1]C[-2],1,0)"
You need to close the formula string, add the address, and then continue:
"=FORECAST.ETS([#Timeline],.address(" & data.address & "),.address(" &
time.address & "):R[-1]C[-2],1,0)"
Note since you're using R1C1 style, you might have to do this on both .address parts,
time.address(ReferenceStyle:=xlR1C1)
so:
"=FORECAST.ETS([#Timeline],.address(" & data.address(ReferenceStyle:=xlR1C1) & "),.address(" &
time.address(ReferenceStyle:=xlR1C1) & "):R[-1]C[-2],1,0)"
Edit: Also, I would change the keyword Time, as I think that's a reserved word. Perhaps Dim timeRng as Range?
In addition to #BruceWayne's answer, to address the first part of your question:
If I have a range B2:B50, and I want the corresponding A column, then I can use the Offset function:
Set time = data.Offset(columnOffset:=-1)
Alternatively you can construct the column like this:
Set time = Sheet1.Range("A2").Resize(Rows(data), 1) 'nrows, 1 column
Then you could put A2 anywhere
FWIW:
range("b2").Select is unnecessary and will really slow down your code if you get into this habit (it's just because the macro recorder doesn't know what you want exactly). You could use Range("B2").Offset(1,1).FormulaR1C1 with no selecting
You can name cells in excel and refer to the names: Range("myNamedCell")
Always best practice to prepend the sheet name and fully qualify references (e.g. Sheet1.Range("A1")) since that will always refer to the same cell, whereas Range("A1") refers to A1 on whichever sheet happens to be selected when you run the macro

Countif with reference to different sheet

Hello I will need help with problem I am facing right now and even Google couldn't help me.
I would like to add to field AS2 a COUNTIF formula with source information from different sheet.
This COUNTIF should jump to sheet ee_lpk and then take a range from column A2 down to the end of last used row. and compare that with criteria from field D.
so for AS2 will be comparing with D2 for AS3 with D3.
When I recorded that it showed:
ActiveCell.FormulaR1C1 = COUNTIF(ee_lkp!R[-143]C[-44]:R[217]C[-44],R[-143]C[-41])"
this is working but just in case that there is on ee_lpk page same number or rows what is changing from day to day.
Any help will be much appreciated.
Martin
You need to break this problem down using variables. Try something like this:
sub Answer()
Dim srcRng as Range
Dim srcLength as Long
'First find how many rows on sheet ee_lpk and store it as a variable
srcLength = Sheets("ee_lkp").UsedRange.Rows.Count
'Then use that variable to get your range
Set srcRng = Range(Cells(2,1), Cells(srcLength, 1))
'Or another viable option would be:
'Set srcRng = Range("A2:A" & srcLength)
'Then put that in your Countif formula
ActiveCell.FormulaR1C1 = _
"=COUNTIF(ee_lkp!" & srcRng.Address(True, True, xlR1C1) & ", R[-143]C[-41])
End Sub

Return cells content from range

Yesterday I learned here how to copy a row to a second sheet.
Sub maJolieProcedure(Texte As String)
With Worksheets("employes").Range("A:A")
Set c = .Find(what:=Texte)
If Not c Is Nothing Then
firstAddress = c.Row
Worksheets("employes").Rows(firstAddress).Copy _
Destination:=Worksheets("rapport").Range("A1")
MsgBox "Ok"
Else
MsgBox "Nok"
End If
End With
End Sub
To respect the formatting of the second sheet, I want to copy and paste the contents of each cell one by one.
I can identify the line number. However, I can't figure out how the Range object can return each cell one by one. For example, C3 content if Rows = 3.
Thanks a lot.
If you don't want to paste the formatting from one range to another paste values only.
Worksheets("employes").Rows(firstAddress).Copy
Worksheets("rapport").Range("A1").PasteSpecial xlValues
That's the same for all ranges, whether 1 cell or a million. The Copy process copies the subject to memory as one block. Any parsing must be done before the Copy instruction. An alternative is to read a range into an array.
Dim Arr As Variant
Arr = Worksheets("employes").Rows(firstAddress).Value
This will create a 3D array of 1 row and about 16000 columns. You might decide to limit your enthusiasm to only what you need.
With Worksheets("employees")
Arr = .Range(.Cells(firstAddress, 1), .Cells(firstAddress, .Columns.Count).End)xlToLeft)).Value
End With
Pay attention to the leading periods within the With statement. Each such period stands for the object mentioned in the With statement.
If your goal is to respect the formating of the second sheet, you don't need to loose time copying cell by cell.
It is more effective to do a paste special, like you do with the mouse:
Range("A1").Copy
Range("B1").PasteSpecial Paste:=xlPasteValues
works very well also with bigger ranges if you need:
Range("A1:A12").Copy
Range("B1:B12").PasteSpecial Paste:=xlPasteValues
or even
Range("A1:A12").Copy
Range("D3").PasteSpecial Paste:=xlPasteValues
If your goal is to really access all cell of a range individually , you just iterate on the range. For example:
For Each cell In Range("A1:A12")
cell.Value = cell.Value + 2
Next cell

Trim string starting at comma - Excel

I have an csv sheet with data of Employee as Last Name, First Name.
Below is an example. (These values are in a single cell)
Flynn, Jeremy
Early, Allison
Epstein, David
Newman, Joanna
Biord, Brooke
I need to left trim the data so that I only need the first name without any trailing space or comma.
OutPut Sample should be:
Jeremy
Allison
David
Joanna
Brooke
How can I write a formula or macro that will process the entire sheet of more that 5000 records.
Formula, in an empty column put:
=TRIM(MID(A1,Find(",",A1)+1,LEN(A1)))
Where A1 is the first cell of your list. Then copy down the entire list.
If you want vba this will do it nearly instantly:
Sub firstName()
Dim rng As Range
With ActiveWorkbook.ActiveSheet
'Change the Second Criterion in Each .Cells() to the column number of your data.
Set rng = .Range(.Cells(1, 1), Cells(.Rows.Count, 1).End(xlUp))
'Change the Offset value to the number of columns to offset the answer.
rng.Offset(, 1).Value = .Evaluate("Index(TRIM(MID(" & rng.Address & ",Find("",""," & rng.Address & ")+1,LEN(" & rng.Address & "))),)")
End With
End Sub
It assumes you data is in column A and it will put it in column B
As a formula in an used column to the right using the REPLACE function,
=REPLACE(A1, IFERROR(FIND(",", A1), LEN(A1)), LEN(A1), TEXT(,))
As a VBA sub procedure using Range.Replace method,
Sub firstOnly_bySel()
With Selection
.Replace what:=",*", replacement:=vbNullString, lookat:=xlPart
'selection.replace(
End With
End Sub
Select one or more cells and run the sub from the Macros dialog ([alt]+[F8])
Just do simple find and replace. Find ",*" and Leave Replace blank.

Have formula to remove all characters to the right of the last char (there might be more then one) problems with vba

The formula =LEFT(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".",""))))-1) to remove all characters to the right of the last . (there might be more then one) works if I add it to a cell and copy down.
I can not figure out how add the formula to vba
I have the vba if there is only one .
(the cells to be evaluated are in column A and the output is to column E )
When I add the code ta a module c.Formula = "=LEFT(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".",""))))-1)" it highlights in red and error Invalid Character with the | highligthed
Thanks
Sub NotWorking()
Dim c As range
Dim Lastrow As Long
With Sheets("sheet1")
Lastrow = .range("C" & .Rows.Count).End(xlUp).Row
For Each c In .range("E2:E" & Lastrow)
c.Formula = "=LEFT(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".",""))))-1)"
Next
.range("E1").Value = "Source"
End With
End Sub
First tip:
when your are usign quotes in formula in VBA, you should use double qoutes. E.g.
instead
Range("E1").Formula="=IF(A1="test",1,2)"
you should use
Range("E1").Formula="=IF(A1=""test"",1,2)"
Second tip:
There is no need to use loop when applying formula. There is a more efficient way to do it.
Next your code
For Each c In .range("E2:E" & Lastrow)
c.Formula = "=LEFT(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".",""))))-1)"
Next
gives you formula for E2 : =LEFT(A2,...), and formula for E3 again =LEFT(A2,...) (note in both formulas A2). I think, it's not what you expected. Use this one instead:
.Range("E2:E" & Lastrow).Formula="=LEFT(A2,FIND(""|"",SUBSTITUTE(A2,""."",""|"",LEN(A2)-LEN(SUBSTITUTE(A2,""."",""""))))-1)"
Above code applies formula to entire range. Formula would be adjusted for each row, e.g. formula for E2 would be =LEFT(A2,...), while formula for E3 would be =LEFT(A3,...) and so on.
But, if you need to have the same formula for entire column E (for E2 : =LEFT(A2,...), and for E3 again =LEFT(A2,...)), use absolute/mixed references (with $ sign):
.Range("E2:E" & Lastrow).Formula="=LEFT(A$2,FIND(""|"",SUBSTITUTE(A$2,""."",""|"",LEN(A$2)-LEN(SUBSTITUTE(A$2,""."",""""))))-1)"
In addition to the points #Simoco makes, you need to adjust the cell refernces in order to get the same effect copying a range gives you, as Excel will automatically adjust these for you (unless you use absolute refernces $), whereas VBA won't.
The easiest way to do this is to use the R1C1 version of cell references.
Try this
Sub Working()
Dim rng As Range
With Sheets("sheet1")
Set rng = Range(.Cells(2, 5), .Cells(.Rows.Count, 3).End(xlUp).Offset(, 2))
End With
rng.FormulaR1C1 = "=LEFT(RC1,FIND(""|"",SUBSTITUTE(RC1,""."",""|"",LEN(RC1)-LEN(SUBSTITUTE(RC1,""."",""""))))-1)"
End Sub

Resources