vba delete do while - excel

I have a problem with one code.
Please help me to fix this.
There is my code :
Sub delete()
Dim i As Long
Dim art As Long
art = 2
x = "programing"
Do While art < Application.WorksheetFunction.CountA(Workbooks("11.xlsm").Worksheets("sheet1").Range("f:f")) + 1
If cell(art, 6).Value <> x Then
cell.ClearContents
End If
art = art + 1
Loop
End Sub

In your code, replace cell with cells.
Secondly you should give the worksheet name as well before cells.
like worksheets(1).cells
If you make these correction, your code will run properly.

You probably made mistake in "cell" must be "Cells".

Related

VLOOKUP and search for different n in the same worksheet

[Edited]
I am so sorry I did not describe this very clear:
My question is about the VLookup function:
I used the code like:
B5'n$CX$"
with the intention to let VBA go to the B5 worksheet and also determine which
"n"(either n25 n35 and so on) it has to go to.
This was not working so I am here to seek if I can get any suggestion.
Below is the original post:
I am very newbie in VBA, just started one or two times touching it.
I have modified the code as below, and my objective is to let
VBA find the values for "DI"&i, depending on the values of "DE"&i
in the spreadsheet B5, but in B5, the number "n" which depends on the
values of "CX"&i, and when VBA goes to look up the values of "DE"&i,
it has to determine the value of n firstly with the help of the values
"CX"&i.
The screenshot of the worksheet B5 is as below:
https://www.dropbox.com/s/do6i7zeylaz0sch/B5.jpg?dl=0
My code is as below:
firstly, if "DE"&i >3.9, I would like VBA set "DI"&i = 0,
else with vlookup function.
Thank you very much for any help and advice.
Appreciated.
Sub FindPl()
For i = 2 To 1730
If .Cells("DE" & i).Value > 3.9 Then .Cells("DI" & i).Value = 0
Else: .Cells("DI" & i).Value =
Application.WorksheetFunction.VLookup($DE$" &
i&",'[C:\Users\chenj5\Documents\Meeting_Jan_2019\simulation of Z1.9 for
Ultra Multi-Focal\Meeting 0220\Dataset used for simulation]B5'n$CX$" &
i&", 2, True)
End If
Next cell
Next i
End Sub
Will take a stab at some example code... I guessed on your source data and fixed some syntax errors... spend some time updating and appropriately dimensioning. There is too much going on/wrong with your posted code to provide anything more clear.
Sub FindPl()
dim i as long, wb as workbook, OUTPUTRANGE as range, SEARCHRANGE as range
set wb = "C:\Users\chenj5\Documents\Meeting_Jan_2019\simulation of Z1.9 for Ultra Multi-Focal\Meeting 0220\Dataset used for simulation.xlsx" 'added xlsx extension
with wb
set OUTPUTRANGE = .range(.cells(5,"D"),.cells(100,"D")) 'guessed... the range with the desired output
set SEARCHRANGE = .range(.cells(5,"B"),.cells(100,"B")) 'guessed... the range where you will find .cells(i,"DE")
end with
with activeworkbook.sheets(1) 'FIX THIS TO FIT YOUR NEEDS
For i = 2 To 1730
If .Cells(i, "DE").Value > 3.9 Then 'FIXED SYNTAX ERROR
.Cells(i, "DI").Value = 0
Else:
.Cells(i, "DI").Value = Application.Index(OUTPUTRANGE, Application.Match(.cells(i, "DE").value,SEARCHRANGE, 0))
End If
Next
end with
End Sub

Excel says no "End Sub", and crashes just by moving cursor

I am writing a VBA code to go through a specified range or ranges, look for a keyword provided by the user at run-time, and grab the value in the cell offset from the cell with the keyword by an amount also provided by the user. For instance, if you wanted to look through A1:B10 for the word "Apple" and then grab the value in the cell to the right of every instance of "Apple", it can do that. Two weird things have been occurring for me. First and not so weird, when I run it and click the cancel button on the userform that only contains the single line "Unload Me", it throws an error saying it expected and End Sub statement, but it has one. I don't know why it is doing that. Weird thing number 2. Whenever I click and move the cursor to the end of the file after the Cancel_Click() sub, my excel crashes and closes. Every. Single. Time. And it is weird that it does that just from me clicking. It also sometimes happens when I click around the Cancel_Click() sub or hit enter around there too. Just simply from clicking. I don't get it. Any ideas? Code contained in the userform is below. Fyi, the user can input ranges like "A1:A10,E1:E10" separated by commas for multiple ranges. I don't think it is important for this question, but I thought I would add that since i don't know how to add the userform here, if you even can.
Private Sub Accept_Click()
'Searches for string input into the KeywordBox
'Grabs contents of the cell defined by the OffsetBox
'The range it searches through is defined by the RangeBox
Dim rawRange As String: rawRange = Me.RangeBox.Text
Dim rawOffset As String: rawOffset = Me.OffsetBox.Text
Dim Keyword As String: Keyword = Me.KeywordBox.Text
Dim numOfRanges As Integer: numOfRanges = 1
Dim Ranges() As Range
Dim commaLoc As Integer: commaLoc = -1
Dim tempRange As String: tempRange = rawRange
Dim offset As Integer
Dim values() As Double
Dim valCount As Integer: valCount = 0
'--------------------------------------------------------
'Set ranges
For i = 1 To Len(rawRange)
If (Mid(rawRange, i, 1) = ",") Then
numOfRanges = numOfRanges + 1
End If
Next
ReDim Ranges(numOfRanges) As Range
If (Not numOfRanges = 1) Then
For i = 1 To numOfRanges - 1
commaLoc = InStr(1, tempRange, ",")
Set Ranges(i) = Range(Left(tempRange, commaLoc - 1))
tempRange = Right(tempRange, Len(tempRange) - commaLoc)
Next
End If
Set Ranges(numOfRanges) = Range(tempRange)
'---------------------------------------------------------
'Set offset
If (IsNumeric(rawOffset)) Then
offset = CInt(rawOffset)
Else:
MsgBox ("Offset was not input as a number")
Exit Sub
End If
'----------------------------------------------------------
'Searches for keyword
For i = 1 To numOfRanges
For Each cell In Ranges(i)
If (cell.Value = Keyword) Then
valCount = valCount + 1
End If
Next
Next
ReDim values(valCount) As Double
valCount = 0
For i = 1 To numOfRanges
For Each cell In Ranges(i)
If (cell.Value = Keyword) Then
valCount = valCount + 1
values(valCount) = cell.offset(0, offset).Value
End If
Next
Next
For i = 1 To valCount
Range("I" & i).Value = values(i)
Next
Unload Me
End Sub
I've had similar, weird things happen to me. A good thing to try is to force the VBA project to reset, then save, exit, and restart Excel.
To force a project reset, add an Enum to the general section of one of your code modules. It doesn't matter what the enum is...make it something simple, like
Enum stoplight
Red
Yellow
Green
End Enum
As you do that, you'll get a message saying that it will reset your project. That's fine; let that happen. Then save your Excel workbook, exit excel completely, start it up again, reload your workbook, go into the VBA Editor, and delete the enum you added. Then recompile and see if things work better for you.
You put an "Exit Sub" in the set offset, this is probably causing your problem.
I was able to fix the issue by making a new workbook and copying everything over. It worked fine. I think the original was corrupted somehow. For those having the same issue, I think Rich Holton's answer would be worth a try in case you have more than just a few things to copy. Thanks everyone for you time and input on this!

Simple excel macro

I have just started to work on Excel macros.
Please let me know what is wrong in the following code:
Sub color_red()
Dim range As range
For R = 1 To 20
If Cells(R, 1).Value = 1 Then range(R, R).Interior.ColorIndex = 3
Next R
End Sub
Error message displayed:
Object variable or with block variable not set
Thanks in advance for your guidance.
You can't use variable name which is any VBA: key word, function, object name, collection name, etc. Try to change your variable name from range into rngTable.
EDIT after additional information written as comments in different areas of that post:
change your if code line into:
If Cells(R,1).Value = 1 Then Cells(R,1).EntireRow.Interior.ColorIndex =3
which will colour all sheet columns in row R. To colour certain range, e.g. in 10 columns you could use this line instead of your if:
If Cells(R,1).Value = 1 Then Cells(R,1).Resize(1,10).Interior.ColorIndex =3
I see that you are still having problem with this code. Please try this simple subroutine, this might be what you need:
Public Sub ColorRowIf()
Dim r As Long
For r = 1 To 20
If Cells(r, 1).value = 1 Then
Cells(r, 1).EntireRow.Interior.ColorIndex = 3
End If
Next r
End Sub
Please also note that using 'Cells()' is not a good way to go, but I have included it for simplicity (as asked). 'Cells()' will always refer to the active sheet cells which might not always be the case. So, instead you should use full reference of the sheet (by code name method) -- so in this example it should say for e.g.: Sheet1.Cells(r,1).Value = 1. Also, remember Sheet1 is not the tab name, its the code name that you see in project window.
#KazJaw is correct, you cannot use a key word as a variable name. But the range or rngTable variable is still used before it is set.
You could still use a Range variable, but why don't you use the same way of addressing as in the if statement?
If Cells(r, 1).Value = 1 Then Cells(r, 1).Interior.ColorIndex = 3
Otherwise you would have to set the range object before you use it:
Set rngTable = Cells(r, 1)
I feel like a lot of people gleaned over the fact your variable 'R' is not defined other than 666bytes.
Declaring the variables you are going to be using is an important thing to do in order to get code to work.
Instead of range you can use the Cells function. You have to refer the WorkSheet for using range. Since nothing is mentioned ,its throwing Object variable or with block variable not set.
Sub color_red()
Dim r As Integer
For r = 1 To 20
If Cells(r, 1).Value = 1 Then Cells(r, r).Interior.ColorIndex = 3
Next r
End Sub

How to make absolute cell ref in loop work and skipping over a column in loop?

I ALMOST got my code working but there are still two things wrong with it (two major things anyway).
1) The absolute cell ref. is not working as it does in Excel. I want for example $A5 but instead of changing to A6 A7 etc., it stays A5 throughout the loop.
2) There is a third column that I need to skip over. I only need my loop to write to columns under VOL and CAP, not %UTIL. How can I tell my loop to skip over $UTIL?
Option Explicit
Dim myRange As Range
Function numberOfRows() As Integer
Debug.Print ("Start test")
ThisWorkbook.Worksheets("LCI").Range("A9").Select
Set myRange = Range(Selection, Selection.End(xlDown))
Debug.Print ("Rows: " & myRange.Rows.Count)
numberOfRows = (myRange.Rows.Count)
End Function
Function numberOfColumns() As Integer
Debug.Print ("Start test")
ThisWorkbook.Worksheets("LCI").Range("B8").Select
Set myRange = Range(Selection, Selection.End(xlToRight))
Debug.Print ("Columns: " & myRange.Columns.Count)
numberOfColumns = (myRange.Columns.Count)
End Function
Sub TieOut(ByVal numberOfRows As Integer, ByVal numberOfColumns As Integer)
Dim i As Integer 'i is row
Dim j As Integer 'j is column
For i = 1 To numberOfRows 'Loop over rows
For j = 1 + 2 To numberOfColumns 'Loop over columns
ThisWorkbook.Worksheets("Loop").Select
With ThisWorkbook.Worksheets("Loop")
**.Cells(i + 3, j + 1).Value = "=INDEX('ZAINET DATA'!$A$1:$H$39038,MATCH(Loop!B$2&TEXT(Loop!$A4,""M/D/YYYY""),'ZAINET DATA'!$C$1:$C$39038,0),4)"
.Cells(i + 3, j + 2).Value = "=INDEX('ZAINET DATA'!$A$1:$H$39038,MATCH(Loop!B$2&TEXT(Loop!$A4,""M/D/YYYY""),'ZAINET DATA'!$C$1:$C$39038,0),5)"**
End With
Next j
Next i
End Sub
Sub Test()
Dim x As Integer
Dim y As Integer
x = numberOfRows()
y = numberOfColumns()
Call TieOut(x, y)
End Sub
Where have you defined it? Is it part of a BAS module?
EDIT: Put Option Explicit as the first line of BAS module & compile (Debug menu -> Compile).
You will see that there are compilation errors.
Remove Dim myRange As Range from Macro1 & Macro2.
Put it at the top of the BAS module (after option explicit)
Note: If you have a variable defined as part of a SUB, other SUB/Functions won't be able to use it. For TieOut to use myRange, it has to be defined at a scope where it can be used by all SUBs.
Also, Macro1 should run first - which assigns the value to MyRange
(i.e. Set MyRange = .....)
If Macro1 is not run, MyRange will hold no value & hence there will be runtime error when your code tries to read the property (MyRange.Rows.Count).
Please take some time to read about Scoping of variables.
A variable needs to hold some value, before you try to read from it.
This is a great example to learn what 'scope' is. You declare (or bring into existence) a variable like the range you're trying to make. It lives inside the macro (or sub procedure) that you made. However, when the sub procedure is finished, your variable no longer has a place to live and gets evicted (dropped out of your computer's memory).
Unfortunately the way your coded your macros will not work the way you are hoping they work. Your myRanges will die everytime they reach an End Sub.
Also when passing arguments (your byvals) to another sub procedure (in this case your TieOut) you must provide the right number of arguments. Your TieOut procedure currently requires two. You cannot pass one and then the other. The correct way would look something like this:
Call TieOut(myRange.Rows.Count, myRange.Columns.Count)
Also you are trying to call a procedure named TieOut2. Not sure if thats a typo, but getting procedure names right is important.
VBA is very powerful and worth learning in my opinion. You look like you are scratching the surface. I would definitely search for some VBA tutorials online. Focus on calling procedures, variable declaration, and scope and I guarantee you will be able to solve your problem :D

How can you make Game of life in Excel? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I know only little how to make macros in Excel.
You can find many examples through Google.
The very first result is a post from David Gainer's blog that uses Conway’s Game of Life to teach about circular reference formulas and iteration (no VBA involved):
http://blogs.office.com/2007/11/02/iteration-conways-game-of-life
Should have done this a long time ago but here's my version of Conway's Life in excel.
Here's a hack of the code. By no means a perfect solution (didn't spend an age on this) but you might be able to pick some bits out.
Private arrGrid(100, 100) As Boolean
Private arrGridNextGeneration(100, 100) As Boolean
Private Sub PopulateParentArrayData()
For k = 1 To Sheet1.Range("C2:AM20").Cells.Count
If Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("A1").Interior.Color Then
arrGrid(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) = True
Else
arrGrid(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) = False
End If
DoEvents
Next
End Sub
Private Sub ApplyParentArrayData()
For k = 1 To Sheet1.Range("C2:AM20").Cells.Count
If arrGrid(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) Then
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("A1").Interior.Color
Else
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("B1").Interior.Color
End If
DoEvents
Next
End Sub
Private Sub ApplyNextGenerationArrayData()
For k = 1 To Sheet1.Range("C2:AM20").Cells.Count
If arrGridNextGeneration(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) Then
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("A1").Interior.Color
Else
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("B1").Interior.Color
End If
DoEvents
Next
End Sub
Private Function GetNeighbourCount(ByVal pintRow As Integer, ByVal pintColumn As Integer) As Integer
Dim intCount As Integer
intCount = 0
For r = pintRow - 1 To pintRow + 1
For c = pintColumn - 1 To pintColumn + 1
If r <> pintRow Or c <> pintColumn Then
If arrGrid(r, c) Then
intCount = intCount + 1
End If
End If
Next c
Next r
GetNeighbourCount = intCount
End Function
Private Sub PopulateNextGenerationArray()
Dim intNeighbours As Integer
For r = 0 To 100
For c = 0 To 100
If r > Sheet1.Range("C2:AM20").Rows(0).Row Then
If r <= Sheet1.Range("C2:AM20").Rows(Sheet1.Range("C2:AM20").Rows.Count).Row Then
If c > Sheet1.Range("C2:AM20").Columns(0).Column Then
If c <= Sheet1.Range("C2:AM20").Columns(Sheet1.Range("C2:AM20").Columns.Count).Column Then
intNeighbours = GetNeighbourCount(r, c)
If arrGrid(r, c) Then
'A1 cell
If intNeighbours < 2 Or intNeighbours > 3 Then
arrGridNextGeneration(r, c) = False
Else
arrGridNextGeneration(r, c) = True
End If
Else
'B1 cell
If intNeighbours = 3 Then
arrGridNextGeneration(r, c) = True
Else
arrGridNextGeneration(r, c) = False
End If
End If
End If
End If
End If
End If
DoEvents
Next c
Next r
End Sub
Private Sub ActionLogic()
'Application.ScreenUpdating = False
PopulateParentArrayData
PopulateNextGenerationArray
ApplyNextGenerationArrayData
'Application.ScreenUpdating = True
End Sub
To get this to work just make the background of cell A1 black, the background of cell B1 white and then add some black backgrounds in the range C2:AM20 and run the ActionLogic method.
You will need two macros. The first one should format the game sheet so the cells are square.
Have the user run this macro. After that she should enter a 1 for each cell that is alive. Use conditional formatting to turn the cell completely black (background = black if value != 0)
Now have a second macro which calculates the next step in a background sheet (another sheet). Use relative cell positioning (relative to ActiveCell) and two nested loops. When this is done, copy all values from the background sheet to the game sheet.
Search for it and look at their code. Plenty of people have made it a hobby to make full games in Excel.
Ex: http://www.geocities.jp/nchikada/pac/
Why do you say Excel is the wrong choice?
I think Excel is the best way to solve this:
Excel solves this with 1 line:
IF(OR(SUM(B2:D4)-C3=3,AND(SUM(B2:D4)-C3=2,C3=1)),1,0)
*where the above is an expression that returns the next generation value for the cell C3.
Here's the demo:
https://docs.google.com/open?id=0B4FcWULw3iQidlZSdG9GRDh0TXM
If you're in a situation where you have to implement this sort of things from scratch, then functional programming is the best way to go. Otherwise, Excel works really well. Why? Because Excel is a system that forces you to enter only pure functions. You see, the key to simulating this Game of Life is to realize that each state of the cells is a PURE FUNCTION of the previous state. Excel naturally forces you to think this way.
another tutorial on circular references in excel can be found here: http://chandoo.org/wp/2009/01/08/timestamps-excel-formula-help/
this one explains how you can insert timestamps using circular references.
Excel is definitely the wrong choice for this kind of a problem. As to how it would be possible: First learn about the game of life and then visual basic to use in Excel.

Resources