vba loop throws error - excel

I have a number of sheets in one excel ..
What I am going to do is consolidate as per the column title into master sheet.
If the column not present in any of the sheets means , filled as “Not available “ in master sheet for those data’s
Below code written by me.. as per my understanding …the code which I pasted here is correct .. but there was a prob in loop .. I don’t where it is ..
Can anyone help me out from this prob …
Sub Sathish()
'Declaration
Dim ii
Dim j As Integer
Dim a As Integer
Dim i As Integer
Dim rrange As Range
Dim trange As Range
'Assigning
a = Worksheets.Count
ii = Array("saaa", "Description", "saaa", "Model", "sathish")
Dim aa As Integer
'Practical
'Call Create_new_sheet
For j = 1 To a
Sheets(j).Select
If Not ActiveSheet.Name = "Master" Then
For i = 1 To 3
Rows("1:1").Select
For Each trange In Selection
If trange.Value = ii(i) Then
Selection.Find(What:=ii(i), After:=ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Copy Destination:=Sheets("Master").Cells(6550, i).End(xlUp).Offset(1, 0)
Else
Sheets("Master").Cells(6550, i).End(xlUp).Offset(1, -1).Select
Selection.End(xlDown).Offset(0, 1).Select
ActiveCell.Value = "[not applicable]"
ActiveCell.Offset(-1, 0).Select
Range(ActiveCell, Selection.End(xlUp)).Offset(1, 0).Select
For Each rrange In Selection
rrange.Value = "[not applicable]"
Next rrange
End If
Next trange
Next i
End If
Next j
End Sub

I was planning to post this as a comment but since there is lot of text, it wouldn't allow me.
Sathish, your understanding of the above problem is almost correct but you missed on few parts.
If trange.Value = ii(i) Then This part will only check first three values of the array. If you notice your loop runs only 3 times (For i = 1 To 3)
Also that is not how .Find is used :) I would recommend going through this link and re-apply the logic.
TOPIC: .Find and .FindNext In Excel VBA (See Section 1)
LINK: http://siddharthrout.wordpress.com/2011/07/14/find-and-findnext-in-excel-vba/
When I write code, I write the logic down and then code accordingly. I would shamelessly recommend this link as well
TOPIC: To ‘Err’ is Human (See Section 1 for what I meant by above. See other sections as well to improve your code)
LINK: http://siddharthrout.wordpress.com/2011/08/01/to-err-is-human/
Here is an example on how the logic would look like.
LOGIC
Loop Through All the worksheets
Check if the Sheet is not Master
Set the search range as 1st row
Use .Find to check if the values in the array is present in row 1. Use a separate loop here.
If found (then do this)
If not found (then do this)
If you are still stuck then post the code that you tried and we will take it from there.
HTH
Sid

Related

Duplicate as Value only last row into adjacent column Excel

I'm creating a VBA application with some forms. When the data is inserted into the Table, Column A calculates a value with a formula. After that I need to copy the resulting value (like paste special, values only) into the adjacent Row
I just need to know how to select the last row everytime. I have tried with ActiveCell, Find, Range etc. but none are working
Selection.Copy
ActiveCell.Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues
Try this:
Selection.Copy
ActiveSheet.Cells(Rows.Count, ActiveCell.Column).End(xlUp).PasteSpecial Paste:=xlPasteValues
From a programming point of view, it's much better to define variables rather than using Selection, .select, or ActiveCell, etc... This code will place the cell you are looking for into the variable r, assuming the first header row (A1) is not empty. If you don't want to make any assumptions about the first or last row, see the last answer on this page. In the code below, this would mean replacing Set r = r.End(xlDown) with Set r = sh.Range("A:A").Find("*", Range("A1"), SearchDirection:=xlPrevious)
Option Explicit
Sub test()
Dim sh As Worksheet, r As Range
Set sh = ThisWorkbook.Worksheets("Sheet1")
Set r = sh.Range("A1")
Set r = r.End(xlDown)
r.Select 'remove after code has been tested and you know it works
End Sub
If you have more questions, just ask. There's a lot of help available to help you program in the proper way here on StackOverflow.
Thanks all,
I fixed it with help of both
LastValue = Range("Table1[Opportunity no.]").End(xlDown).Value
Set ws = Worksheets("Datos")
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row
With ws
.Cells(iRow, 2).Value = LastValue
End With

VBA Excel Subtotal Dynamic Ranges Not Working

I have this snippet of code that I've borrowed from other post and edited(or at least tried) that I'm trying to use to subtotal some dynamic ranges. I use a key column with 0's, 1's, and 2's. I want the code to add all the coorosponding columns across from each 1 until it hits a 2 and then put the subtotal in the column with the 2. Currently, my code keeps running backwards so it is putting the wrong subtotals in. Below is a snippet of my code.
'count all 1's in each section till next 2 for subtotaling each section
With Range("P13:P" & lRow1)
Set rFind = .Find(What:=2, LookIn:=xlFormulas, SearchOrder:=xlByRows, _
Lookat:=xlWhole, SearchDirection:=xlNext, searchFormat:=False)
If Not rFind Is Nothing Then
s = rFind.Address
Do
Set r1 = rFind
Set rFind = .FindNext(rFind)
If rFind.Address = s Then
Set rFind = .Cells(.Cells.Count)
r1.Offset(, -5).Value = Application.Sum(Range(r1.Offset(-1, -5), r1.Offset(, -5)))
Exit Sub
End If
r1.Offset(, -5).Value = Application.Sum(Range(r1.Offset(-1, -5), rFind.Offset(, -5)))
Loop While rFind.Address <> s
End If
End With
Even now that I type this question out I'm thinking I should take a different approach. My code places a 0 at each blank line and I currently have it set to place a 0 on the line above the 1st 1. With that, I could maybe find the 1st 0 then add all the 1's till i reach a 2 then find the next 0 and so forth. Does that make sense?
Below is a picture of what the macro is currently producing.
You can actually do this with a formula
=IF(P3=2,SUMIF($P$1:P2,1,$K$1:K2)-SUMIF($P$1:P2,2,$K$1:K2),"")
in each cell in K where there is a 2 in column P. Could use VBA to insert this.
Here's a straight VBA solution:
Sub x()
Dim r As Range
For Each r In Range("K:K").SpecialCells(xlCellTypeConstants).Areas
r(r.Count + 1).Value = Application.Sum(r)
Next r
End Sub

VBA Macro with offset

I'm trying to create a simple macro for a sheet I use every day at work.
Basically it's about:
Sheet 1 Cell A2:A11 has values in it those values need to be copy pasted into sheet 2 to with an offset each day to the next free column.
What I've got so far is the copy paste with one offset...but I don't know how to say that the offset should happen for the next free column.
Dim rng As Range
Dim ws As Worksheet
Range("A2:A11").Select
Selection.Copy
Sheets("Sheet2").Select
If rng Is Nothing Then
'if nothing found - search for last non empty column
Set rng = ws.Range("2:2").Find(What:="*", LookAt:=xlWhole, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
If rng Is Nothing Then
Set rng = rng.Offset(, 1)
ActiveSheet.Paste
End If
If I understand correctly, try just using this instead of all your current code
Range("A2:A11").Copy Sheets("Sheet2").Cells(2, Columns.Count).End(xlToLeft).Offset(, 1)
Set rng = rng.End(xlToRight).Offset(0, 1)
You go all the way right and then one more for the next free column.

Using Excel Macros to replace text quickly if the cell is a certain value

I have a macro that's met to find all the rows in the N column in an excel spreadsheet with a value of 'Accept', and adjust their value to 'Reject'.
My macro is working, but it works VERY slow, it literally took me over 15 minutes for my macro to run through 20,000+ rows changing the cell value from Accept to Reject, which is way too long for me to expect any customer to wait (20,000 is the high end of how many rows of data I'd expect customers to have).
Below is the code in my macro, I'm wondering if anyone has any ideas how I can make it run faster.
' Select cell N2, *first line of data*.
Range("N2").Select
' Set Do loop to stop when an empty cell is reached.
Do Until IsEmpty(ActiveCell)
If ActiveCell.Value = "Accept" Then
ActiveCell.Value = "Reject"
End If
' Step down 1 row from present location.
ActiveCell.Offset(1, 0).Select
Loop
Thanks for all the help guys. I used some of the links and code you guys posted (especially the link Doug Glancy posted in a comment, wish I could pick comments as the accepted answer) to come up with some new code that works almost instantly. For anyone who's interested in how it's working, here's the new VBA code.
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = Range("N2:N" & ActiveSheet.UsedRange.Rows.Count)
dat = rng ' dat is now array
For i = LBound(dat, 1) To UBound(dat, 1)
If dat(i, 1) = "Accept" Then
dat(i, 1) = "Reject"
End If
Next
rng = dat ' put new values back on sheet
The following has worked very fast for me in the past:
Have macro select area/range that needs to have values replaced.
Selection.Replace What:="Accept",Replacement:="Reject", LookAt:=xlPart, SearchOrder:=xlByRows,MatchCase:=True,SearchFormat:=False,ReplaceFormat:=False
Try this:
Sub formatnumbers()
Do Until IsEmpty(ActiveCell)
ActiveCell.Select
ActiveCell.Replace What:=ActiveCell.Value, Replacement:=ActiveCell.Value, LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
ActiveCell.Offset(2000, 0).Select
Loop
End Sub

Copy and paste last used column into next available column

I know this has probably already been answered but I have searched through the previous questions and cannot find an answer that works for me.
Basically I have an excel spreadsheet which can be updated daily/weekly/monthly depending on the workflow. What I need is a macro that finds the last 'used' column(Headers are in row 5), inserts a blank column directly to the right of that - (we have a totals table at the end that needs to move along) & copies the entire last used columns data into that newly created column.
It's probably quite a simple code but I've only just started using VBA and hope someone can help!! I'm hoping once I've started doing some bits and pieces I can build up my knowledge!
Thanks in advance
Emma
From here: Copy last column with data on specified row to the next blank column and here: Excel VBA- Finding the last column with data
Sub Test()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim rLastCell As Range
Dim LastCol As Integer
Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
LastCol = rLastCell.Column
ws.Columns(LastCol).Copy ws.Columns(LastCol + 1)
End Sub
Lazy minimalist solution:
Sub Macro1()
Dim col As Integer
col = Range("A5").End(xlToRight).Column
Columns(col).Copy
Columns(col + 1).Insert Shift:=xlToRight
End Sub
Though this will crash if there's nothing in cell A5.

Resources