Excel Mac VBA Loop Through Cells and reset some values - macos

I currently have a worksheet that I have multiple people filling out every day. There are 4 columns that the users fill out: C, E, H, & J (all numerical values, one row per day of the month.)
The users fill in C, E, & H every day no matter what, but a lot of days there is no value to put in column J. I need the value in J to be set to 0 if the user doesn't enter anything. Of course it would be easier to just have the users enter 0, but I'm working with a complicated group of people here.
Anyway, I want to use a macro that runs automatically when the user clicks the save button (before it actually saves, of course), and have it do the following: (I am more familiar with php, so I'm just typing this out how I'm familiar - I'm sure my syntax is incorrect)
Foreach Row
If "column A" != "" {
If "column J" != "" {
//Everything is good, continue on...
} else {
CurrentRow.ColumnJ.value == 0
}//Value has been set - continue loop
}
//column A is blank, this day hasn't come yet - quit looping here
End Foreach
If anyone could help me out with this I'd appreciate it. With some research, this is what I've come up with so far, and now I'm stuck…
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim curCell As Range
'Labor Flow Sheet'.Select
For Each curCell in Range( ???? )
If curCell.Value = "" Then
???????
End If
Next curCell
End Sub
Thanks in advance!

See this link about finding the right range, and as for the question marks inside the If statement, you would want to put
curCell.Value = 0

For the question marks in your statement
For Each curCell in Range( ???? )
Solution 1:
To find the full range you're working with, you'll need to use a column that is filled out each day. You mentioned columns C, E, and H were filled out every day. Using one of those columns (let's pick C for the example here), you could find the range by using the .end method. This goes out either up down left or right from a range until it doesn't find any data. So,
Range("J1", Range("C1").End(xlDown)).Select
will select all cells from J1 (or whatever column is the last in your sheet) to the bottom-most cell containing data in column C, automatically.
Solution 2:
Manually put in the range. For example, to choose A1 to J300:
Range("A1", "J300").Select

Related

Excel 2010 VBA Macro making excel freeze

I have a big block of data >50 across and >1500 down and some of the entries are very large negative numbers like -1000000 or -9820000 and I want all of those to be turned into -100's.
I also want any non-zero numbers that are above -100 to show 2 decimals.
I thought this vba macro would work, but its causing excel to freeze and the excel screen turns all grey and idk whats happening.
I think it might be because there are so many cells, so it takes a long time and over loads something, is there any way to make this code more efficient??
Sub Blah()
For ColNum = 2 To WorksheetFunction.CountA(Range("1:1"))
For RowNum = 2 To WorksheetFunction.CountA(Range("A:A"))
If Cells(RowNum, ColNum) < -101 Then Cells(RowNum, ColNum) = -100
If Cells(RowNum, ColNum) <> 0 And Cells(RowNum, ColNum).Value > -100 Then Cells(RowNum, ColNum).NumberFormat = "0.00"
Next RowNum
Next ColNum
End Sub
Although Tmdean pointed out the solution, I'll post a sample code which might be of help.
Edit1: It seems assigning negative value in cell took a while as well. So apply the same principle. Get the relevant cells first and assign value in one go.
Sub marine()
Dim r As Range, c As Range, nonzero As Range, s As Range
Set r = ActiveSheet.UsedRange
For Each c In r
Select Case True
Case c.Value <= -101
'~~> Identify the cells first and combine all of them, don't assign value
If s Is Nothing Then Set s = c _
Else Set s = Union(s, c)
Case c.Value <> 0 And c.Value > -100
'~~> Identify the cells first and combine all of them, do not format
If nonzero Is Nothing Then Set nonzero = c _
Else Set nonzero = Union(nonzero, c)
End Select
Next
'~~> Once you got all the cells, assign value in one go
If Not s Is Nothing Then s.Value = -100
'~~> Once you got all the cells, format in one go
If Not nonzero Is Nothing Then nonzero.NumberFormat = "0.00"
End Sub
You can replace this with your For Loop, whatever is easier.
You can also be more explicit on setting the Range Object instead or using UsedRange. HTH.
There's nothing in that code that's particularly slow. How many cells are you changing? The only suggestion I have is to set the NumberFormat for the entire range beforehand (to 0.00), then turn set it back to General only for the cells that are 0 or -100 in your loop. Changing the NumberFormat is probably the most expensive operation, so you want to minimize the times you set it for individual cells.
Someone will be here shortly to recommend you turn off Application.ScreenUpdating.

Sorting data by groups in Excel

So, I've looked around and tried to solve this on my own. This isn't an absolutely crucial question currently, I just want to know if it could be done.
So let's say I've got a list with some data that looks like
Date Location
01/24/14 H-12
01/25/14 BB-44
01/30/14 G-12
01/29/14 7A-55
01/28/14 NN-15
01/24/14 GG-47
What I want is to be able to sort the data by Location, but I don't want it to be the general way, otherwise I'll end up with 7A-55, BB-44, G-12, H-12, NN-15. I want the data to be sorted so that double letters and single letters are sorted together. E.G. it should be G-12, H-12, BB-44, NN-15, 7A-55 once everything has been sorted.
I've tried creating a custom list sort, but it doesn't work. the way intended. The custom list I tried was A-Z, AA-ZZ, 7A (items were listed out, but for saving space I wrote them like that).
Like I said, this isn't a particularly huge deal if it can't be done, it just would have made it a little easier.
Edit 1 Here is what I would like to be the output
Date Location
01/30/12 G-12
01/24/14 H-12
01/25/14 BB-44
01/24/14 GG-47
01/28/14 NN-15
01/29/14 7A-55
Edit
All of these worked in the regards i wanted to, although if I had to choose a favorite it would be the base 36 number conversion one. That was some real out-of-the-box thinking and the math geek in me appreciated it. Thanks everyone!
Well it works, but is a bit complex, so rather just for fun:
This UDF returns a value that can be used as sort key. It transforms the code into a four-digit base 36-number, i.e. using A-Z and 0-9 as symbols (like hex uses 0-9 and A-F). To get at your desired output, I literally put the symbols in this order, letters first (so "A" = 0 and "0" = 26).
(The missing 'digits' are filled up with zeros, which are in this case "A"s)
It works ;)
Public Function Base36Transform(r As Range) As Long
Dim s As String, c As String
Dim v
Dim i As Integer
Dim rv As Long
v = Split(r.Text, "-")
s1 = v(0)
s2 = v(1)
s = Right("A" & s1, 2) & Right("A" & s2, 2)
rv = 0
For i = 1 To Len(s)
c = Mid(s, Len(s) - i + 1, 1)
If c Like "#" Then
rv = rv + (Val(c) + 26) * (36 ^ (i - 1))
Else
' c is like "[A-Z]"
rv = rv + (Asc(c) - Asc("A")) * (36 ^ (i - 1))
End If
Next
Base36Transform = rv
End Function
Sorting is often a very creative process. VBA can ease up the process, but a little extension of the data will work just as well.
See my results:
The way I did it is by getting the length of each string, just to be safe. This is gotten by simply going =LEN(B2), dragged down.
Then I check if it starts with 7. If it does, assign 1, otherwise keep at 0. I used this formula: =(LEFT(B2,1)="7")*1, dragged down.
Now, my custom sort is this:
Now I might have gotten some things wrong here, or I might even have done overkill by going the Length column. However, the logic is pretty much what you're aiming for.
Hope this helps in a way! Let us know. :)
I am a little lazy here and assuming your data sits in Column A,B. You mightneed to adjust your range or the starting point of your list. But here's the code:
Sub sortttttt()
Dim rng As Range
Dim i As Integer
Range("B2").Activate
Do While Not IsEmpty(ActiveCell)
ActiveCell.Value = Len(ActiveCell.Value) & ActiveCell.Value
ActiveCell.Offset(1, 0).Activate
Loop
Set rng = Range("A1:B6")
rng.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlYes
Range("B2").Activate
Do While Not IsEmpty(ActiveCell)
ActiveCell.Value = Right(ActiveCell.Value, Len(ActiveCell.Value) - 1)
ActiveCell.Offset(1, 0).Activate
Loop
End Sub
Assuming your data is in columns B:C with labels in Row1 and no intervening blank rows, add a column with:
=IF(ISNUMBER(VALUE(LEFT(C2))),3,IF(FIND("-",C2)>2,2,1))
in D1 copied down to suit and sort ascending Location within sort ascending of the added column.

How to I create a loop that uses the last column in an array as the starting point for the next loop? In matlab

I have output = A(:,Nout) Nout = points along the array..... : = all points in column
So, it is saying the values in the last column.
How do I use output as A at the first column for the next iteration?
Your question is not clear. You may mean a variety of things.
If you want to loop through values in the first column in some order specified by your last column you can:
Asort = A ( A (:, end), :);
and then loop through Asort.
You may also mean to loop N times for each row where N is defined by last column of A.
You can do it using a nested loop:
for Arow = A(:, end)
for ii = 1:Arow
% your code here
end
end
You may also mean several other things, but instead me guessing you could try clarifing a bit. :)
(it should be a comment but I can't add comments yet, sorry)

Visual Basic Function Procedure

I need help with the following H.W. problem. I have done everything except the instructions I numbered. Please help!
A furniture manufacturer makes two types of furniture—chairs and sofas.
The cost per chair is $350, the cost per sofa is $925, and the sales tax rate is 5%.
Write a Visual Basic program to create an invoice form for an order.
After the data on the left side of the form are entered, the user can display an invoice in a list box by pressing the Process Order button.
The user can click on the Clear Order Form button to clear all text boxes and the list box, and can click on the Quit button to exit the program.
The invoice number consists of the capitalized first two letters of the customer’s last name, followed by the last four digits of the zip code.
The customer name is input with the last name first, followed by a comma, a space, and the first name. However, the name is displayed in the invoice in the proper order.
The generation of the invoice number and the reordering of the first and last names should be carried out by Function procedures.
Seeing as this is homework and you haven't provided any code to show what effort you have made on your own, I'm not going to provide any specific answers, but hopefully I will try to point you in the right direction.
Your first 2 numbered items look to be variations on the same theme... string manipulation. Assuming you have the customer's address information from the order form, you just need to write 2 separate function to take the parts of the name and address, take the data you need and return the value (which covers your 3rd item).
To get parts of the name and address to generate the invoice number, you need to think about using the Left() and Right() functions.
Something like:
Dim first as String, last as String, word as String
word = "Foo"
first = Left(word, 1)
last = Right(word, 1)
Debug.Print(first) 'prints "F"
Debug.Print(last) 'prints "o"
Once you get the parts you need, then you just need to worry about joining the parts together in the order you want. The concatenation operator for strings is &. So using the above example, it would go something like:
Dim concat as String
concat = first & last
Debug.Print(concat) 'prints "Fo"
Your final item, using a Function procedure to generate the desired values, is very easily google-able (is that even a word). The syntax is very simple, so here's a quick example of a common function that is not built into VB6:
Private Function IsOdd(value as Integer) As Boolean
If (value Mod 2) = 0 Then 'determines of value is an odd or even by checking
' if the value divided by 2 has a remainder or not
' (aka Mod operator)
IsOdd = False ' if remainder is 0, set IsOdd to False
Else
IsOdd = True ' otherwise set IsOdd to True
End If
End Function
Hopefully this gets you going in the right direction.

QTP narrow a list of ChildObjects

[The description is a bit fudged to obfuscate my real work for confidentiality reasons]
I'm working on a QTP test for a web page where there are multiple HTML tables of items. Items that are available have a clickable item#, while those that aren't active have an item# as plain text.
So if I have a set of ChildObjects like this:
//This is the set of table rows that contain item numbers, active or not.
objItemRows = Browser("browserX").Page("pageY").ChildObjects("class:=ItemRow")
What is the simplest way in QTP land to select only the clickable link-ized item #s?
UPDATE: The point here isn't to select the rows themselves, it's to select only the rows that have items in them (as opposed to header/footer rows in each table). If I understand this correctly, I could then use objItemRows.Count to count how many items (available and unavailable) there are. Could I then use something like
desItemLink = Description.Create
desItemLink("micclass").value = "Link"
objItemLinks = objItemRows.ChildObjects(desItemLink)
To get the links within only the item rows?
Hope that clarifies things, and thanks for the help.
I think I have this figured out.
Set desItemLink = description.create
desItemLink("micclass").value = "Link"
desItemLink("text").RegularExpression = True
//True, Regex isn't really required in this example, but I just wanted to show it could be used this way
//This next part depends on the format of the item numbers, in my case, it's [0-9]0000[0-9]00[0-9]
For x = 0 to 9
For y = 0 to 9
For z = 0 to 9
strItemLink = x & "0000" & y & "00" & z
desItemLink("text").value = strItemLink
Set objItemLink = Browser("browser").Page("page").Link(desItemLink)
If objItemLink.Exist(0) Then
//Do stuff
End If
Next
Next
Next
Thanks for your help anyways, but the code above will iterate through links with names in a given incrementing format.

Resources