Column referencing in VBA using sheet().Range().Value - excel

I'm trying to avoid copy and paste in order to dramatically speed up a Macro (previously taking two minutes to run). I am trying to reference four entire columns in Sheetx(A,B,J,L) and have them display in sheety(A6,B6,C6,D6).
I have tried a number of variations of
Sheets("Sheety").Range("A6:A,B6:B,C6:C, D6:D").Value = Sheets("Sheetx").Range("A:A, B:B, J:J, L:L").Value
Also, for sheets("sheety") I tend towards Active.Sheet or Sheets(B) as I have used the index number for the sheet ie
For B = 31
31 being the index number for the real sheet.
I have been searching for answers for the last hour. Can anyone help?

Tell me if something like this:
Sub Testy3()
Dim N As Long
N = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
Sheets("Sheet1").Range("A1:A" & N).Copy Sheets("Sheet2").Range("A6")
End Sub
works for you.
If all the columns in Sheet1 have the same number of rows, then you don't need to re-calculate N for each column.

Related

Find the last row/column in excel using access VBA

I am trying to run a for loop from start to end of all of the data in my excel sheet that is being processed by access vba. I have tried:
myWorksheet.Cells(Rows.Count, 4).End(xlUp).row
but it did not work. I am confused how I can get a one number output so that it is able to run in my loop successfully. Please help. Also, if you could break down the format of your answer that would really help me. Thanks
Access has not constant xlUp which has value -4162 in Excel. In Access xlUp is non-declared variable with Variant type and initial value Empty. To use proper End(xlUp) in Access VBA you can write .End(-4162):
myWorksheet.Cells(myWorksheet.Rows.Count, 4).End(-4162).row
I usually define my LastRow like so, with "N" that's just the column that has the data in it, you can adjust that as needed:
LastRow = ActiveSheet.Cells(Cells.Rows.Count, "N").End(xlUp).Row
I usually pair that with a Dim row_no As Long and use it in the loop like so, the hard number here being the first row of my dataset.
For row_no = 5 to LastRow
'Do the thing
Next
There's way to iterate through loops in reverse order, which makes more sense when you're deleting rows, because when you delete it row it messes with what row the macro thinks it's on. Ie: you delete row 2, so row 3 moves to row 2, but the macro moves to row 3 which has the 4th row of data. For those you'll approach it like so:
For x = LastRow To 5 Step -1
'Do the thing
Next x

Excel: Calculate difference between cell and cell above in an auto filtered table

I have a table with column A containing incrementing numerical values, and column B being a bunch of names. I need to filter the table according the names, and have column C update with the difference between the value in column A in the current row and the cell above..
For example, I'd like to have something like this
which,
when filtered according to the Name column, should update the difference like so
I have tried to use SUBTOTAL function in a few different ways but to no avail. Ideally it'd update once the filter in the table is changed. I tried to do this in VBA but so far I've gotten macro that only filters with the hard-coded filter criteria.
Solutions in either excel formulas/python/vba are all welcomed and greatly appreciated!
I apologise in advance if this question isn't up to standards as Im new here :) Thank you in advance!
#JvdV: This is the outcome of me trying to implement your formula, This is after filtering.
REVISED ANSWER
So after your explenation I have looked into a formula that will give you the difference of the current row B-value minus the B-value of occurance of the A-value before that.
=IFERROR(B2-LOOKUP(2,1/($A$1:A1=A2),$B$1:B2),0)
Taking your sample data, it would look like this:
Then when you apply the filter, it would look like this:
So with this workaround you dont have the correct value when no filter is applied, but in this case I assumed you are interested in the difference when it IS filtered!
The formula is entered in cell C2 and dragged down.
EDIT
If this is not the answer you'r after and you DO need the values when it is not filtered, make use of a UDF like below:
Public Function LastVisibleCell(CL As Range) As Long
Dim RW As Long, X As Long
RW = CL.Row - 1
On Error GoTo 1
If RW > 1 Then
For X = RW To 1 Step -1
If ActiveSheet.Rows(X).EntireRow.Hidden Then
Else
LastVisibleCell = Cells(CL.Row, 2).Value - Cells(X, 2).Value
Exit For
End If
Next X
Else
1: LastVisibleCell = 0
End If
End Function
Call it from cell C2 like: =LastVisibleCell(A2) and drag down. When you apply your filter, the cells will update.
Beware, this will take ages to update on large datasets!
After 3 days of intense (albeit ineffective) Google-ing, I finally came across this answer also on stack overflow.
However, as I'm working on a large set of data (>150,000 rows), the method in the question uses too much memory. Using VBA to paste the formulas into visible cells only does not seem to alleviate the problem.
Sub CopyPasteFormula()
Dim Ws As Worksheet
Dim LRow As Long
Dim PasteRng As Range
Set Ws = Worksheets("Translated Data")
Ws.Range("$D$2:$D$200000").AutoFilter Field:=4, Criteria1:="<>-", Operator:=xlFilterValues
LRow = Ws.Range("D" & Rows.Count).End(xlUp).Row
Set PasteRng = Ws.Range("A3:A" & LRow).SpecialCells(xlCellTypeVisible)
Ws.Range("A3").Copy
PasteRng.PasteSpecial xlPasteFormulas
Application.CutCopyMode = False
End Sub
Above is my macro code to attempt reduce the memory use... Appreciate any feedback!

VBA search range for =TODAY()+30 and clear contents

Somewhat experienced with excel but very new to VBA and looking for some help. I have a range (D:AE) containing dates. Each column has a variable number of rows but the total number of used cells will be no less than ~1500 and may go as high as 10,000. I am trying to create a macro that will find any date within this range greater than 30 days from today and then subsequently clear that same cell's contents. The end result will be dates only falling within the next 30 days. I've done some pretty extensive searching but the limits of my experience haven't left me with much. Any help would be greatly appreciated!
Build a For ... Next loop to look at every column in your sheet, like
For C = 1 To ActiveSheet.UsedRange.Columns.Count
Nest another such loop inside the first, like,
For R = 2 To ActiveSheet.UsedRange.Rows.Count
Within this second loop, each cell is ActiveSheet.Cells(R, C) and you can test and manipulate it. Like,
With ActiveSheet.Cells(R, C)
If IsDate(.Value) Then
If CDate(.Value) > (Date + 30) Then
.Value = ""
End If
End If
End With

Record a variation of a cell - excel

my problem is:
I have a matrix in excel then a function (repeated N times) that extract from this matrix a random number.
This happen everytime i hit F9 or everytime something change in the sheet.
After this i have another cell with a sum of all then numbers extracted. I would like to keep track of the change of this last cell in a linear chart to see how it goes on.
Thank you so much in advance
Solution 1: formulas
if you want to repeat T times, just instead of only 1 series of N number create a matrix of N by T. Then ad 1 last row (or column) under (or next to) the N functions for all T which contains the sum.
Now relate a chart to this last row (or column).
Solution 2: VBA
Create a piece of code that loops T times and copies the value of the cell with the sum into the next empty cell in a designate part of your excel workbook.
Sub aaa
dim i as Long
dim T as Long
T = 1000
For i = 1 to T
Range("rSum").Copy
Cells(rows.count,1).offset(xlUp)).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
Next i
End Sub

Excel-VBA Comparing Column Data

I am completely new to Excel VBA, and I need to write code to do a simple task. I need to compare values in two different columns row by row, and see if the difference exceeds 50. If so, I need to highlight the entire row.
I program in other languages, so I have a basic understanding for how this works, but I have no clue how to navigate cells/view the content inside the cells. I tried this but it didn't work out (it would just highlight every single row). I simplified it to compare if values are equal or not, but to no avail (still everything is highlighted) Can anyone give me some help?
Dim strF0_col As Integer, sF0_col As Integer
Dim myRow, counter As Integer
Dim rEnd As Integer
Sub compare_F0()
rEnd = 100
strF0_col = 307
sF0_col = 317
counter = 0
For myRow = 2 To rEnd Step 1
Application.StatusBar = counter & "rows highlighted."
If (Cells(myRow, strF0_col).Value = Cells(myRow, sF0_col).Value) Then
Cells(myRow, strF0_col).EntireRow.Interior.ColorIndex = 28
End If
Next myRow
End Sub
Thanks in advance
Is there any reason to do not use Conditional Formatting, as #Doug Glancy suggested?
It worked quite fine here for me.
In case you want to give it a shoot, do as follows...
Choose the whole row
Open Conditional Formatting Menu (will depend on your Excel version. Anyway...)
Add the Rule =$KU2>$LE2+50
Set the format you want (maybe fill in yellow?)
Confirm
Copy format to other rows
Notice the row index (2, in this case) cannot have the $ symbol.
Hope it helps.
You probably don't want to highlight rows that are blank?
If so, use
If Cells(myRow, strF0_col).Value <> "" And _
Cells(myRow, strF0_col).Value = Cells(myRow, sF0_col).Value Then
As an aside, accessing cell values like this is quite slow. If you are only processing 100 rows then its fast enough, but if this number grows then you will find it slows down to a painful degree.
It is much faster to copy the range values to a variant array an then loop over that. Search SO for [Excel] "Variant Array" There are many answers that show how to do this and explain why it helps

Resources