VBA Selecting cells when it shouldn't with IF Range.Text = "True"? - vba

I have the following code, which is a work in progress, but VBA keeps saying the If Range("G"&CRow).text = "True" then is true in the highlighted row, when it obviously isn't. Can anyone help me figure this out?
Range("G1").FormulaR1C1 = _
"=IF(OR(ISNUMBER(SEARCH(""GS "",RC[-6])),ISNUMBER(SEARCH(""#"",RC[-6]))),""TRUE"",""FALSE"")"
Range("G1").AutoFill Destination:=Range("G1:G" & lastrow)
With Range("G1:G" & lastrow)
.Value = .Value
End With
Dim T As Integer
Dim CRow As Integer
CRow = 1
For Each cell In Range("G1:G" & lastrow)
If Range("G" & CRow).Text = "TRUE" Then
cell.Select
ActiveCell.Offset(0, -5).Select
If Selection.Value = "" Then
Selection.Resize(, 4).Select
Selection.Delete Shift:=xlUp
ActiveCell.Offset(2, 0).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
CRow = CRow - 1
End If
Else
CRow = CRow + 1
End If
Next

BECAUSE of this
CRow = 1
For Each cell In Range("G1:G" & lastrow)
If Range("G" & CRow).Text = "TRUE" Then
You are assiging 1 to CRow and using that in each iteration. So actually you are always testing Just Row 1.
Change Range("G" & CRow).Text to cell.Text

See below example to delete the same group of cells using a reverse loop and not selecting. I believe I interpreted, and thus changed, this line properly ActiveCell.Offset(2, 0).Select, but let me know if I'm mistaken and it doesn't function as expected.
Range("G1").FormulaR1C1 = _
"=IF(OR(ISNUMBER(SEARCH(""GS "",RC[-6])),ISNUMBER(SEARCH(""#"",RC[-6]))),""TRUE"",""FALSE"")"
Range("G1").AutoFill Destination:=Range("G1:G" & lastrow)
With Range("G1:G" & lastrow)
.Value = .Value
End With
Dim T As Integer
For T = 1 to lastrow Step -1
Set cell = Range("G" & T)
If cell.Text = "TRUE" Then
If cell.offset(0,-5) = "" Then
cell.Offset(0,-5).Resize(,4).Delete Shift=xlUp
Range("G" & T + 2).Insert Shift:=xlDown CopyOrigin:=xlFormatFromLeftOrAbove
End If
End If
Next

Related

VBA Loop through strings

I have to loop through a serious of variables to filter the contents of a dataset to paste it to other sheets. The code I have to paste the data is as follows
Sheets("Source").Select
LastRow = ActiveSheet.Range("A1").Offset(ActiveSheet.Rows.Count - 1, 0).End(xlUp).Row
If ActiveSheet.AutoFilterMode = False Then ActiveSheet.AutoFilterMode = True 'Enable Filters if not exists
ActiveSheet.Range("$A$3:$AY$" & LastRow).AutoFilter Field:=4, Criteria1:= _
"SelectionABC"
Range("A3:AY" & LastRow).Copy
Sheets("DestinationX").Select
Range("A4").Select
ActiveSheet.Paste
The source is always the same, but the "SelectionABC" and the "DestinationX" will change. The selection and detonation are paired, so "SelectionABC" goes to sheet "Destination1", "SelectionDEF" goes to sheet "Destination2",...
How can I loop through the selection & destination so that I don't have the repeat the code for each data transfer?
Here is a quick untested code to help you get going.
Dim i, j As Long
Dim alpha As String
Dim b As Boolean : b = False
j = 1
'~~> UPPERCASE ALPHABETIC CHARACTERS IN THE
'~~> ASCII TABLE GO FROM 65="A" TO 91="Z"
For i = 65 To 91
If i = 89 Then '~~> BECAUSE WE ARE LEFT WITH LAST TWO LETTERS "YZ"
alpha = Chr(i) & Chr(i + 1)
b = True '~~> TO COME OUT OF LOOP AFTER "YZ"
Else
alpha = Chr(i) & Chr(i + 1) & Chr(i + 2)
i = i + 2
End If
Sheets("Source").Select
LastRow = ActiveSheet.Range("A1").Offset(ActiveSheet.Rows.Count - 1, 0).End(xlUp).Row
If ActiveSheet.AutoFilterMode = False Then ActiveSheet.AutoFilterMode = True 'Enable Filters if not exists
ActiveSheet.Range("$A$3:$AY$" & LastRow).AutoFilter Field:=4, Criteria1:= _
"Selection" & alpha '~~> ADDED alpha here
Range("A3:AY" & LastRow).Copy
Sheets("Destination" & j).Select '~~> ADDED j HERE
Range("A4").Select
ActiveSheet.Paste
j = j + 1
If b Then Exit For '~~> TO COME OUT OF LOOP AFTER "YZ"
Next

excel vba code corrupting my file consistently after a few runs

I have a relatively long set of subs that get run on a list of my excel files a few times a day. after a few runs, the file then becomes corrupted which normally would not be an issue b/c it doesn't really effect any of the data. however, I have another program that opens up each of the excel and pulls some key data from each one to make a summary sheet. because the corrupted file gives a message that says something along the lines of "there is a problem with some of your content" the summary program stops with a
run-time error '1004': Method of object 'Workbooks' Failed
I can not for the life of me figure out what in my code is causing the corruption. Is there a way I can have the summary code ignore the corruption notification? Ive tried a handful of different things including turning the application notifications off in my code to no avail.
Any help is greatly appreciated! ill post my all my code with a brief description below:
Here is the code from the summary file that opens each of the
individual files and pulls data:
Sub OEEsummmary()
Dim ActCycCell, ExpCycCell, ExpCurCycCell, ShiftCell, DifCell, DownCell, DTResACell, DTResBCell, PartCell, OpNamCell, OprCell, RejCell, RejResCell As Range
Dim MySheet As Worksheet
Dim Txt$, MyPath$, MyWB$
Dim myValue As Integer
Dim x As Long
Dim v As Variant, r As Range, rWhere As Range
MyPath = "L:\Manufacturing Engineering\Samuel Hatcher\"
x = 2
Set MySheet = ActiveSheet
'Application.ScreenUpdating = False
Application.EnableEvents = False
MySheet.Range("B2:G18").ClearContents
MySheet.Range("J2:O18").ClearContents
Do While MySheet.Range("A" & x).Value <> ""
MyWB = MySheet.Range("A" & x).Text
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True
Set ActCycCell = ActiveSheet.Range("E21")
Set ExpCycCell = ActiveSheet.Range("D21")
Set ShiftCell = ActiveSheet.Range("E2")
Set DownCell = ActiveSheet.Range("K28")
Set DTResACell = ActiveWorkbook.Worksheets("Downtime").Range("O9")
Set DTResBCell = ActiveWorkbook.Worksheets("Downtime").Range("O10")
Set PartCell = ActiveSheet.Range("E4")
Set ExpCurCycCell = ActiveSheet.Range("D22")
If ActiveSheet.Range("I3") = "" Then
Set OpNamCell = ActiveSheet.Range("I2")
Else
Set OpNamCell = ActiveSheet.Range("I3")
End If
Set OprCell = ActiveSheet.Range("C4")
Set RejCell = ActiveSheet.Range("H21")
Set RejResCell = ActiveWorkbook.Worksheets("Rejected Parts").Range("H5")
With MySheet.Range("A" & x)
.Offset(0, 14).Value = OprCell.Value
.Offset(0, 13).Value = OpNamCell.Value
.Offset(0, 12).Value = PartCell.Value
.Offset(0, 11).Value = ShiftCell.Value
.Offset(0, 10).Value = RejResCell.Value
.Offset(0, 9).Value = RejCell.Value
.Offset(0, 6).Value = ActCycCell.Value
.Offset(0, 5).Value = ExpCycCell.Value
.Offset(0, 4).Value = ExpCurCycCell.Value
.Offset(0, 3).Value = DTResBCell.Value
.Offset(0, 2).Value = DTResACell.Value
.Offset(0, 1).Value = DownCell.Value
End With
ActiveWorkbook.Close savechanges:=False
x = x + 1
Loop
Call sort
'Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Clears the page of data to prepare it for a new shift of entering
data:
Sub ClearFrontEnd()
Sheets("Front End").Unprotect ("29745")
'prompts user to confirm if they realy want to clear entry
response = MsgBox("Are You Sure?", vbYesNo)
If response = vbNo Then
Exit Sub
End If
'checks to see if operator number is there
If range("I3").Value = "" Then
MsgBox "ENTER OPORATOR # AND CLICK NEW SHIFT AGAIN"
Else
Call StopTimer
Call prodChoose
Call transfer
Application.ScreenUpdating = False
ActiveWorkbook.Save
Sheets("Front End").Unprotect ("29745")
Sheets("Front End").Select
'Deletes the data from the entry and unique key fields
range("E8:E20").ClearContents
range("I8:I27").ClearContents
range("J8:J27").ClearContents
range("K8:K27").ClearContents
range("I3").ClearContents
range("H8").Value = ""
range("H9").Value = ""
range("H10").Value = ""
range("H11").Value = ""
range("H12").Value = ""
range("H13").Value = ""
range("H14").Value = ""
range("H15").Value = ""
range("H16").Value = ""
range("H17").Value = ""
range("H18").Value = ""
range("H19").Value = ""
range("H20").Value = ""
range("A1").Select
MsgBox "Please enter the correct values for SHIFT #, SHIFT LENGTH, PART #, AND OPORATOR #, Thanks! Have a great day!!"
End If
Sheets("Front End").Protect ("29745")
Call timerchoose
Application.ScreenUpdating = True
End Sub
This copies the data from the front page to a raw data sheet every
hour:
Sub transfer()
Sheets("Front End").Unprotect ("29745")
Application.ScreenUpdating = False
Dim x As Long
Dim v As Variant, r As range, rWhere As range
'set starting point at row 8
x = 8
'defines the sheet the data is being coppied from and pasted to
Dim sourceSheet As Worksheet: Set sourceSheet = ThisWorkbook.Worksheets("Front End")
Dim destSheet As Worksheet: Set destSheet = ThisWorkbook.Worksheets("Raw Data")
If sourceSheet.range("I3").Value = "" Then
Call StartTimer
Exit Sub
Else
Do While range("L" & x).Value <> ""
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("M" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("J" & x).Value
destSheet.range("C" & lMaxRows + 1).Value = sourceSheet.range("K" & x).Value
destSheet.range("D" & lMaxRows + 1).Value = sourceSheet.range("L" & x).Value
destSheet.range("E" & lMaxRows + 1).Value = sourceSheet.range("I" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("M" & x).Value
x = x + 1
Else
x = x + 1
End If
Loop
x = 8
Do While range("D" & x).Value <> 0
If range("E" & x).Value <> "" Then
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("A" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("B" & x).Value
destSheet.range("L" & lMaxRows + 1).Value = sourceSheet.range("C" & x).Value
destSheet.range("F" & lMaxRows + 1).Value = sourceSheet.range("D" & x).Value
destSheet.range("G" & lMaxRows + 1).Value = sourceSheet.range("E" & x).Value
destSheet.range("I" & lMaxRows + 1).Value = sourceSheet.range("G" & x).Value
destSheet.range("K" & lMaxRows + 1).Value = sourceSheet.range("H" & x).Value
destSheet.range("H" & lMaxRows + 1).Value = sourceSheet.range("N" & x).Value
destSheet.range("J" & lMaxRows + 1).Value = sourceSheet.range("O" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("A" & x).Value
x = x + 1
Else
x = x + 1
End If
Else
x = x + 1
End If
Loop
'sorts Raw Data table after new data is added
Dim ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("Raw Data")
'specifies how to sort the data
With ws.Sort.SortFields
.Clear
.add Key:=ws.range("A2:A" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.add Key:=ws.range("B2:B" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
'specifies range over which to sort
End With
With ws.Sort
.SetRange ws.range("A1:S" & lMaxRows + 1)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
Sheets("Front End").Protect ("29745")
Call SortDTWeek
Call SortDTMonth
Call StartTimer
Application.ScreenUpdating = True
End Sub
This checks a few cells constantly to see if they have been double
clicked, if so it puts the current time in that cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As range, cancel As Boolean)
'Adds downtime start and finish values
'Check to see if the click/selected cell is in columns I or J
If Not Intersect(Target, range("J:K")) Is Nothing Then
'Make sure cell is in range
If Target.Row > 7 And Target.Row <= 27 Then
'Update the value
Target.Value = Time()
End If
End If
End Sub
Checks to see if a set of cells has been changed, if so it puts the
now() value in a corresponding "key" column
Private Sub Worksheet_Change(ByVal Target As range)
Sheets("Front End").Unprotect ("29745")
Dim cell As range
'Adds unique keyA values
'Check to see if the changed cell is in column E
If Not Intersect(Target, range("E:E")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And Target.Row > 7 And Target.Row <= 20 Then
'Update the "KeyA" value
Sheets("Front End").range("A" & Target.Row).Value = Now()
End If
Next cell
Else
'Adds unique keyB values
'Check to see if the changed cell is in column K
If Not Intersect(Target, range("K:K")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And (Target.Row > "6" And Target.Row <= "27") Then
'Update the "KeyM" value
range("M" & Target.Row).Value = Now()
End If
Next cell
End If
End If
Sheets("Front End").Unprotect ("29745")
End Sub
thanks for any input this issue has been driving me crazy
as #MLind suggested in the comments, to bypass the corrupted file error and pull some data out i added this to my code:
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True,
CorruptLoad:=xlExtractData
and used
Application.DisplayAlerts = False
within the loop to prevent any pop up boxes from stopping the sub

comparing a single value against an array in VBA

Sub CHECKas()
Dim lastrow As Long
Dim lastcol As Long
Dim l As Integer
Dim i As Integer
Dim rname As Constants
Set rngTarg = Selection
lastrow = Sheets("report").Range("B" & Rows.Count).End(xlUp).row
lastcol = Sheets("report").Cells(2, Columns.Count).End(xlToLeft).Column
Sheets("FEBBRAIO").Select
ActiveCell.Offset(0, -3).Copy
Sheets("REPORT").Select
Cells(1, lastcol + 1).PasteSpecial xlPasteAll
Application.CutCopyMode = False
rname = Application.ActiveCell.Value
ActiveCell.Offset(1, 0).Select
For i = 2 To lastrow
ThisWorkbook.Sheets("report").Select
If Range("f2:f" & lastrow) <= Val(CStr(rname.Value)) _
And Range("g2:g" & lastrow) > Val(CStr(rname.Value)) Then
Cells(i, ActiveCell.Column).Value = "1"
Else
Cells(i, ActiveCell.Column).Value = 0
End If
Next i
End Sub
I'm new in VBA and I can't understand how to compare a constant value with each cell in a range("g2:g" & lastrow) and ("f2:f" & lastrow). The constant value is an active cell in my case. For example considering this formula: IF(AND($R$1<G2;$R$1>=f2);1;0 where R$1$ is the active cell of the last not empty column in ROW 1. I need to fill the entire column (that is activecell.column) with the output coming out form this formula.
But the I Got mismatch error in:
If Range("f2:f" & lastrow) <= Val(CStr(rname.Value)) _
And Range("g2:g" & lastrow) > Val(CStr(rname.Value)) Then
Cells(i, ActiveCell.Column).Value = "1"
Else
Cells(i, ActiveCell.Column).Value = 0
End If
I know from the previous question that this error occurs because I'm trying to comparing a single value against an array of values. How can fix this problem?
You have to use
Range("F" & i)
in your code. Same thing applies to other instances of such code.

How to split and restructure cells using excel VBA

The code I currently use splits:
And changes it to:
However, this is the format in which I require the data to be in:
This is a copy of my current code:
Sub SplitCells()
Dim rColumn As Range
Dim lFirstRow As Long
Dim lLastRow As Long
Dim lRow As Long
Dim lLFs As Long
Set rColumn = Columns("D")
lFirstRow = 1
lLastRow = rColumn.Cells(Rows.Count).End(xlUp).Row
For lRow = lLastRow To lFirstRow Step -1
lLFs = Len(rColumn.Cells(lRow)) - Len(Replace(rColumn.Cells(lRow), vbLf, ""))
If lLFs > 0 Then
rColumn.Cells(lRow + 1).Resize(lLFs).EntireRow.Insert xlShiftDown
rColumn.Cells(lRow).Resize(lLFs + 1).Value = Application.Transpose(Split(rColumn.Cells(lRow), vbLf))
End If
Next lRow
End Sub
Any help/comments will be appreciated.
call ResizeToFit macro at the end of your code
Add ResizeToFit right before End Sub in your current code
ie.
...
Next lRow
ResizeToFit ' or Call ResizeToFit
End Sub
...
add this code to the same module as a new sub
Sub ResizeToFit()
Application.ScreenUpdating = False
Dim i As Long
For i = Range("D" & Rows.Count).End(xlUp).Row To 1 Step -1
If IsEmpty(Range("D" & i)) Then
Rows(i & ":" & i).Delete
Else
Range("E" & i) = Split(Range("D" & i), Chr(32))(1)
Range("D" & i) = Split(Range("D" & i), Chr(32))(0)
End If
Next i
For i = 1 To 5
If i <> 4 Then
Cells(1, i).Resize(Range("D" & Rows.Count).End(xlUp).Row, 1).Value = Cells(1, i)
End If
Next
Application.ScreenUpdating = True
End Sub
Taking THIS
and running my code produces
Sub SplitCells()
Dim rColumn As Range
Dim lFirstRow As Long
Dim lLastRow As Long
Dim lRow As Long
Dim lLFs As Long
Set rColumn = Columns("D")
lFirstRow = 1
lLastRow = rColumn.Cells(Rows.Count).End(xlUp).Row
For lRow = lLastRow To lFirstRow Step -1
lLFs = Len(rColumn.Cells(lRow)) - Len(Replace(rColumn.Cells(lRow), vbLf, ""))
If lLFs > 0 Then
rColumn.Cells(lRow + 1).Resize(lLFs).EntireRow.Insert xlShiftDown
rColumn.Cells(lRow).Resize(lLFs + 1).Value = Application.Transpose(Split(rColumn.Cells(lRow), vbLf))
End If
Dim curRow As Integer
curRow = lRow + lLFs
While curRow >= lRow
If Application.CountA(Rows(curRow).EntireRow) = 0 Then
Rows(curRow).Delete
Else
rColumn.Cells(curRow).Offset(0, 1).Value = Split(rColumn.Cells(curRow), " ")(1)
rColumn.Cells(curRow).Value = Split(rColumn.Cells(curRow), " ")(0)
rColumn.Cells(curRow).Offset(0, -3).Value = rColumn.Cells(lRow).Offset(0, -3).Value
rColumn.Cells(curRow).Offset(0, -2).Value = rColumn.Cells(lRow).Offset(0, -2).Value
rColumn.Cells(curRow).Offset(0, -1).Value = rColumn.Cells(lRow).Offset(0, -1).Value
End If
curRow = curRow - 1
Wend
Next lRow
End Sub
This is just from a recorded macro so it needs cleaning up.
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],LEN(RC[-1])-5)"
Range("E1:E4").Select
Selection.FillDown
Range("F1").Select
ActiveCell.FormulaR1C1 = "=RIGHT(RC[-2],4)"
Range("F1:F4").Select
Selection.FillDown
Range("E1:F4").Select
Selection.Copy
Range("E1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("D:D").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
You may not need the cut, paste and column delete if you're happy with Column D staying as it is and having the split parts to the right. In which case
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],LEN(RC[-1])-5)"
Range("E1:E4").Select
Selection.FillDown
Range("F1").Select
ActiveCell.FormulaR1C1 = "=RIGHT(RC[-2],4)"
Range("F1:F4").Select
Selection.FillDown
Sorry - ActiveCell is E1.

Loop through columns with conditional if in Excel [duplicate]

This question already has answers here:
Run-Time error 1004 Excel 2013
(2 answers)
Closed 6 years ago.
I'm needing to write an excel script to fill in some data. Essentially what needs to happen is the script should loop through each record and when it hits a "1" it should follow each cell with another "1" until it hits the next "1". My goal is to fill in the gaps between 1s with more 1s.
Here's what I have so far:
Dim i, j As Integer
finalrow = Cells(665, 1).End(x1up).Row
finalcol = Cells(1, 10).End(x1toleft).Column
For i = 1 To finalrow
If Cells(i, j).Value = "0" Then
For j = 1 To finalcol
Next j
Else
For j = 1 To finalcol
Next j
Cells(i, j).Value = "1"
End If
Next i
I keep getting an error when this is ran.
My data is structured like this:
0 0 1 0 0 0 1 0 0 0
1 0 0 1 0 0 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 1 1 0 0 0 0 0
Any help or advise is much appreciated.
Thanks.
There are a few issues with your code (particularly that FOR LOOP doesn't make much sense).
I took what you had and made comments and changed to quasi-fit what you are asking for.
Absorb:
Option Explicit 'USE THIS!!!
Sub Test()
'Dim i, j As Integer NO! "i" is Varaint and you want integer
Dim i As Integer, j As Integer 'Use this syntax for single line declaration
'Adding "Option Explicit" makes you declare these two variables
Dim finalRow As Integer
Dim finalCol As Integer
Dim oneFound As Boolean 'This will be used on the for loop
finalRow = Range("A65536").End(xlUp).Row 'Do this. I'm not sure your code works: Cells(665, 1).End(xlUp).Row 'you had x1, not "XL" (typo)
finalCol = Range("IV1").End(xlToLeft).Column ''Do this. I'm not sure your code works: Cells(1, 10).End(xlToLeft).Column 'had x1, not "XL" (typo)
oneFound = False
For i = 1 To finalRow 'You're looping through rows here, now you need to loop through columns
'REASON FOR YOUR ERROR: Variable j below is zero at this point and there is no cell (1,0).
'If Cells(i, j).Value = "0" Then
For j = 1 To finalCol
If Cells(i, j).Value = 1 And Not oneFound Then 'We found a one in a cell and we haven't started in filling ones yet
oneFound = True
ElseIf Cells(i, j).Value <> 1 And oneFound Then 'You found a one previously in the row and you want to start filling in data
Cells(i, j).Value = 1
ElseIf Cells(i, j).Value = 1 And oneFound Then 'You found a one previously in the row and you just found your next one
'Don't know what you want to do here
'Setting oneFound to false in case you want to stop filling in data
oneFound = False
Else
'All scenarioes should be covered for what you asking above.
'You could do something else here should you find the need
End If
Next j
oneFound = False 'Reinitialize for next row
Next i
End Sub
If all you are trying to do is replace zeros with ones, instead of looping through the data you could use search and replace functionality.
Cells.Select
Selection.Replace What:="0", Replacement:="1"
Sub abc()
j = 2
ActiveSheet.Range("a1").Select
ActiveSheet.Range("a65536").Select
lastrow = Selection.End(xlUp).Row
'/// column a
ActiveSheet.Range("a3:a" & lastrow).Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$A$" & lastrow).AutoFilter Field:=1, Criteria1:="="
Application.CutCopyMode = False
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("Sheet2").Select
lrow = ActiveSheet.Range("A65536").End(xlUp).Row
ActiveSheet.Range("a" & lrow).Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.EntireRow.Delete
Selection.AutoFilter
'column b///////////
ActiveSheet.Range("b3:b" & lastrow).Select
Selection.AutoFilter
ActiveSheet.Range("$b$1:$b$" & lastrow).AutoFilter Field:=1, Criteria1:="="
Application.CutCopyMode = False
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("Sheet2").Select
lrow = activehseet.Range("A65536").End(xlUp).Row
ActiveSheet.Range("a" & lrow).Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.EntireRow.Delete
Selection.AutoFilter
'column c////////////
ActiveSheet.Range("c3:c" & lastrow).Select
Selection.AutoFilter
ActiveSheet.Range("$c$1:$c$" & lastrow).AutoFilter Field:=1, Criteria1:="SG Plus", _
Operator:=xlOr, Criteria2:="=Select"
Application.CutCopyMode = False
Range(Selection, Selection.End(xlToRight)).Select
' Selection.Copy
' Sheets("Sheet2").Select
' lrow = activehseet.Range("A65536").End(xlUp).Row
' ActiveSheet.Range("a" & lrow).Select
' ActiveSheet.Paste
' Sheets("Sheet1").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.EntireRow.Delete
Selection.AutoFilter
'column c again/////////////
ActiveSheet.Range("c3:c" & lastrow).Select
Selection.AutoFilter
ActiveSheet.Range("$c$1:$c$" & lastrow).AutoFilter Field:=1, Criteria1:="="
Application.CutCopyMode = False
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("Sheet2").Select
lrow = activehseet.Range("A65536").End(xlUp).Row
ActiveSheet.Range("a" & lrow).Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.EntireRow.Delete
Selection.AutoFilter
'//////////////////////////// changes oct 21 end
ActiveSheet.Range("a1").Select
For i = 3 To lastrow
Range("a" & i).Select
If Range("a" & i).Value = "MidAmerica" Or Range("a" & i).Value = "Northeast" Or Range("a" & i).Value = "Southeast" Or _
Range("a" & i).Value = "West" Then
GoTo cont
Else
Rows(i).Select
Application.CutCopyMode = False
Selection.Cut
Sheets("Sheet2").Select
Range("a" & j).Select
ActiveSheet.Paste
j = j + 1
Sheets("sheet1").Select
Selection.Delete Shift:=xlUp
End If
cont:
Next i
'/////// column b ///////////
ActiveSheet.Range("a1").Select
For i = 3 To lastrow
Range("b" & i).Select
If Range("b" & i).Value = "CA" Or Range("b" & i).Value = "AZ" Then
GoTo cont2
Else
Rows(i).Select
Application.CutCopyMode = False
Selection.Cut
Sheets("Sheet2").Select
Range("a" & j).Select
ActiveSheet.Paste
j = j + 1
Sheets("sheet1").Select
Selection.Delete Shift:=xlUp
End If
cont2:
Next i
'///////////column c //////////
ActiveSheet.Range("a1").Select
For i = 3 To lastrow
Range("c" & i).Select
If Range("c" & i).Value = "SG" Then
GoTo cont3
Else
Rows(i).Select
Application.CutCopyMode = False
Selection.Cut
Sheets("Sheet2").Select
Range("a" & j).Select
ActiveSheet.Paste
j = j + 1
Sheets("sheet1").Select
Selection.Delete Shift:=xlUp
End If
cont3:
Next i
'//////////column l/////////////
ActiveSheet.Range("a1").Select
For i = 3 To lastrow
Range("l" & i).Select
If Range("l" & i).Value >= "01/01/2014" And Range("l" & i).Value <= "30/06/2014" Then
GoTo cont4
Else
Rows(i).Select
Application.CutCopyMode = False
Selection.Cut
Sheets("Sheet2").Select
Range("a" & j).Select
ActiveSheet.Paste
j = j + 1
Sheets("sheet1").Select
Selection.Delete Shift:=xlUp
End If
cont4:
Next i
'//////////column m/////////////
ActiveSheet.Range("a1").Select
For i = 3 To lastrow
Range("m" & i).Select
If Range("m" & i).Value >= "12/01" Or Range("m" & i).Value <= "12/05" Then
GoTo cont5
Else
Rows(i).Select
Application.CutCopyMode = False
Selection.Cut
Sheets("Sheet2").Select
Range("a" & j).Select
ActiveSheet.Paste
j = j + 1
Sheets("sheet1").Select
Selection.Delete Shift:=xlUp
End If
cont5:
Next i
'//////////column q and r/////////////
ActiveSheet.Range("a1").Select
For i = 3 To lastrow
Range("q" & i).Select
If Range("q" & i).Value <> " " And Range("r" & i).Value <> " " And Range("u" & i).Value <> " " _
And Range("z" & i).Value <> " " And Range("aa" & i).Value <> " " And Range("ab" & i).Value <> " " _
And Range("b" & i).Value <> " " And Range("j" & i).Value <> " " Then
GoTo cont6
Else
Rows(i).Select
Application.CutCopyMode = False
Selection.Cut
Sheets("Sheet2").Select
Range("a" & j).Select
ActiveSheet.Paste
j = j + 1
Sheets("sheet1").Select
Selection.Delete Shift:=xlUp
End If
cont6:
Next i
End Sub
you could do that with the use of a formula and replace the existing values like this:
Sub Test2()
Dim iRow As Integer
Dim iDx As Integer
Dim iLastRow As Integer
Dim sConcatValues As String
Dim sFormula As String
sConcatValues = "A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J"
sFormula = "=LEFT(" & sConcatValues & ",FIND(""1""," _
& sConcatValues & ")) & REPT(""1"",FIND(""1""," _
& sConcatValues & ",FIND(""1""," _
& sConcatValues & ")+1)-1-FIND(""1""," _
& sConcatValues & ")) & MID(" _
& sConcatValues & ",FIND(""1""," _
& sConcatValues & ",FIND(""1""," _
& sConcatValues & ")+1),LEN(" _
& sConcatValues & "))"
iLastRow = Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row
iRow = 1
' put in the formula to fix the values
Range("L1:L" & iLastRow).Formula = sFormula
Range("L1:L" & iLastRow).Copy
Range("L1:L" & iLastRow).PasteSpecial xlPasteValues
' now copy over the new values, and clean up!
For iRow = 1 To iLastRow
For iDx = 1 To Len(Range("L" & iRow).Text)
Cells(iRow, iDx) = Mid(Range("L" & iRow).Text, iDx, 1)
Next
Next
Range("L1:L" & iLastRow).Clear
'Range("A1").Activate
End Sub
this is the formula that is used:
=LEFT(A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J,FIND("1",A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J)) & REPT("1",FIND("1",A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J,FIND("1",A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J)+1)-1-FIND("1",A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J)) & MID(A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J,FIND("1",A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J,FIND("1",A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J)+1),LEN(A:A&B:B&C:C&D:D&E:E&F:F&G:G&H:H&I:I&J:J))
basically you concatenate the cells, then do a find for the first 1, followed by the next 1, and fill in between using the REPT function
Philip
Including this might help as well.
http://msdn.microsoft.com/en-us/library/office/aa213567%28v=office.11%29.aspx
Cells.SpecialCells(xlCellTypeLastCell)
Instead of using
finalRow = Range("A65536")...
finalCol = Range("IV1").End(xlToLeft).Column