Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
TheAngryDrunk
Jan 31, 2003

"I don't know why I know that; I took four years of Spanish."

factorialite posted:

I have a crazy question.

I've created an excel file with the each nfl team's schedule on it, and on each page I also have a ranking system. In this file, I've created a tab called Alpha Tab that has a column for each team and a column for ratings (so you can put your own rating system there). I want to use a function to lookup the name of whatever tab I'm in and pull the value to the right of that name in the tab "alpha tab."

For example, I am in the Miami tab. I want to write a function that says "I am in miami, let me go to the alpha tab and return the value just to the right of miami."

Is this possible? The spreadsheet makes heavy use of calling value from other tabs, so I know that can be done. However, I did it using brute force, and it'd be nice to learn how to do this.

Thanks in advance!


You need a custom function to spit out the worksheet name on a worksheet.

Here's how to do it: http://www.ozgrid.com/VBA/return-sheet-name.htm

Once you have that, you can use that in your lookup functions.

Adbot
ADBOT LOVES YOU

factorialite
Mar 3, 2008

by Lowtax

TheAngryDrunk posted:

You need a custom function to spit out the worksheet name on a worksheet.

Here's how to do it: http://www.ozgrid.com/VBA/return-sheet-name.htm

Once you have that, you can use that in your lookup functions.

This is a lot of help, but I'm not there yet.

If I wanted to grab detroit's rating while on the chicago tab, I would enter

='Detroit'!a13.

Now, I need to use the LOOKUP function to grab the value to the right of whatever the tab name that sheetname() gives me. I've got the sheetname() function but I don't know which lookup to use. I thought it'd be VLOOKUP but I can't specify across sheets with that, can I? I'm imagining that INDIRECT will come into play, but I'm not sure how to combine the two successfully. Thanks again for both your expedient response and any other help you might give!

ZerodotJander
Dec 29, 2004

Chinaman, explain!
The vlookup range can be on another sheet, sure.

=VLOOKUP(SHEETNAME(),'Alpha Tab'A:B,2,FALSE)

Or something along those lines should work.

kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison
I've got data set up like so:
code:
Dept.   Phone Number   Other Stuff
100     5555555555     Name
200     5555555551     Name
300     5555555552     Name
300     5555555553     Name
400     5555555554     Name
And so forth. What I'm trying to do is coax a macro into copying each row into a pre-existing set of sheets based on the first column. (ie, workbook already created with a sheet for each dept)

Would there be a way to do this with one master macro, rather than having a macro for every department? I'm not really familiar with VB, but any sort of guidance would be appreciated.

gwar3k1
Jan 10, 2005

Someday soon
Not the most efficient way, but it will do what you've asked:

code:
Sub CopyData()
  iRow = 1
  Do While Cells(iRow, 1) <> ""
    'Get department name and copy data
    sDept = Cells(iRow, 1)
    Range("A" & iRow & ":C" & iRow).Select
    Selection.Copy
    
    'Paste to department sheet (last row of)
    Sheets(sDept).Select
    Range("A" & NextFreeRow(sDept)).Select
    ActiveSheet.Paste
    
    'Repeat
    Sheets("masterlist").Select
    iRow = iRow + 1
  Loop
End Sub

Function NextFreeRow(sSheet)
  iCur = 1
  Do While Sheets(sSheet).Cells(iCur, 1) <> ""
    iCur = iCur + 1
  Loop
  NextFreeRow = iCur
End Function

kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison

gwar3k1 posted:

Not the most efficient way, but it will do what you've asked:

It was failing, but I see what the problem is. This should work okay, thanks!

Ok, no, it's still failing. It's giving 'subscript out of range' after a few rows, and it's skipping the first two sheets. I thought that maybe it was checking the object name instead of what the sheet was named, but it doesn't seem to be the case.

kitten emergency fucked around with this message at 23:13 on Oct 9, 2010

gwar3k1
Jan 10, 2005

Someday soon

serewit posted:

It was failing, but I see what the problem is. This should work okay, thanks!

Ok, no, it's still failing. It's giving 'subscript out of range' after a few rows, and it's skipping the first two sheets. I thought that maybe it was checking the object name instead of what the sheet was named, but it doesn't seem to be the case.

I've made the assumption that your department sheets are named exactly the same as the department code. Also, I have made the assumption that there is a sheet for every department on your master list sheet.

I bet its saying subscript out of range because a sheet name doesn't match / the intended sheet doesn't exist.

Can you provide an example of department code and sheet name, and say which line is causing the exception (highlighted yellow ehen you click debug).

kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison

gwar3k1 posted:

I've made the assumption that your department sheets are named exactly the same as the department code. Also, I have made the assumption that there is a sheet for every department on your master list sheet.

I bet its saying subscript out of range because a sheet name doesn't match / the intended sheet doesn't exist.

Can you provide an example of department code and sheet name, and say which line is causing the exception (highlighted yellow ehen you click debug).

code:
4	5555555555	JSIN 
5	5555555555	SERGEY
6	5555555555	SERGEY B
20	5555555555	PILLERIN
30	5555555555	PLIKSA 
54	5555555555	VLADIMIR
54	5555555555	MAKSYM 
100	5555555555	ANGELA 
100	5555555555	ALRIC E
100	5555555555	LOANER 
100	5555555555	PAT
Error occurs on this line, once it hits the sixth row (54)
code:
 Sheets(sDept).Select
I do have sheets for every value in the first column, including 54. Additionally, it's skipping the first two sheets I have in the book (For instance, I have sheets named 4, 5, 6, 20, 30. It puts '6' under sheet '30'. The records for 20 and 30 never even appear, errors out as soon as it hits row 6 (code 54))

ed: the sheets are set up as follows
code:
(Main) (4) (5) (6) (20) (30) (54) (100) (200) (300) (etc)

gwar3k1
Jan 10, 2005

Someday soon

serewit posted:

stuff


It needs to be run from the main sheet. Here's some ammended code:
code:
Sub CopyData()
  iRow = 1
  SHeets("Main").Select
  Do While Cells(iRow, 1) <> ""
    'Get department name and copy data
    sDept = trim(Cells(iRow, 1))
    Range("A" & iRow & ":C" & iRow).Select
    Selection.Copy
    
    'Paste to department sheet (last row of)
    Sheets(sDept).Select
    Range("A" & NextFreeRow(sDept)).Select
    ActiveSheet.Paste
    
    'Repeat
    Sheets("Main").Select
    iRow = iRow + 1
  Loop
End Sub

Function NextFreeRow(sSheet)
  iCur = 1
  Do While Sheets(sSheet).Cells(iCur, 1) <> ""
    iCur = iCur + 1
  Loop
  NextFreeRow = iCur
End Function

kitten emergency
Jan 13, 2008

get meow this wack-ass crystal prison

gwar3k1 posted:

It needs to be run from the main sheet. Here's some ammended code:

Works brilliant! Thank you!

edit: would you care for a plat upgrade? let me know - username at gmail dot com.

kitten emergency fucked around with this message at 00:17 on Oct 10, 2010

gwar3k1
Jan 10, 2005

Someday soon
edit: ^^^ No thanks, just glad I could help someone for a change. I'm always asking.

Not really a coding question, but I have a template that does multiple functions (Add client, edit client, etc.) and I want the users to be able to select these functions from the ribbon.

Calling the template from the ribbon opens the template and not a regular copy of it. How can I make the ribbon force template functions to open as non-template functions? Or should I just disable saving (they shouldn't require the need to save anything anyway).

This is an example line from the ribbon customizations:
code:
<mso:button idQ="x1:C:_wamp_www_admin_AddClients.xltm_ThisWorkbook.ADD_CLIENTS_0_14E0275B" 
label="1 - Clients" imageMso="CondolatoryEvent" 
onAction="C:\wamp\www\admin\AddClients.xltm!ThisWorkbook.ADD_CLIENTS" visible="true"/>

gwar3k1 fucked around with this message at 21:23 on Oct 12, 2010

factorialite
Mar 3, 2008

by Lowtax
Thanks for the help guys, I'm very nearly there!

My next problem is a really weird one.

I've got the sheetname(a1) function defined, that's no problem.
I think I've got the vlookup function correct (I use =vlookup(sheetname($a$1,true),'Master'!$a$1:$b$33,2). This actually does pull the data I want it to... most of the time.

If I have this data in master:
pre:
Chicago	        1
Detroit	        2
Minnesota	3
Green Bay	4
NY Giants	5
The vlookup returns the following results:
pre:
Chicago         1
Detroit         2
Minnesota       4
Green Bay       4
NY Giants       5
If I extend the data a little further:
pre:
Chicago	        1
Detroit	        2
Minnesota	3
Green Bay	4
NY Giants	5
Dallas          6
It becomes:
pre:
Chicago         1
Detroit         2
Minnesota       6
Green Bay       6
NY Giants       6
Dallas          1
I don't really have any idea why it does this. Any ideas?

esquilax
Jan 3, 2003

factorialite posted:


Try changing your formula to:

=vlookup(sheetname($a$1,true),'Master'!$a$1:$b$33,2, false)

When you don't specify a last argument for a vlookup, it defaults to "True". This makes it look for an 'approximate' value, which gives you weird results if your list isn't in alphabetical order. Setting it as 'False' makes it look for an exact match, and you don't have to reorder anything.

factorialite
Mar 3, 2008

by Lowtax

esquilax posted:

Try changing your formula to:

=vlookup(sheetname($a$1,true),'Master'!$a$1:$b$33,2, false)

When you don't specify a last argument for a vlookup, it defaults to "True". This makes it look for an 'approximate' value, which gives you weird results if your list isn't in alphabetical order. Setting it as 'False' makes it look for an exact match, and you don't have to reorder anything.

false gives me the N/A error.

If I do sheetname(a1,false), it still works, so it likely isn't the sheetname function that screws me up. If I have to alphabetize, it's not optimal but it's doable for sure.

TheAngryDrunk
Jan 31, 2003

"I don't know why I know that; I took four years of Spanish."

factorialite posted:

false gives me the N/A error.

If you're getting an N/A with the last argument set to 'false,' but it works with 'true' then the exact value you're looking up isn't on the list.

Also, make sure your formula has expanded to include the new data.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
nevermind

IT Guy fucked around with this message at 15:53 on Nov 1, 2010

GerbilNut
Dec 30, 2004
I've got two questions I could really use a hand on.

First, i've got a pivot table setup with a filter for Invoice Numbers and the need to select multiple items. When just one invoice is select, the drop down box shows that invoice number. If more than one is selected it just shows (Multiple Items). Is there a way to get a copy of the multiple items select to print on the report without manually typing them in somewhere?


Secondly, I also have a Data Validation list with hundreds of choices referencing data in another sheet of a workbook. Is it possible to get it to filter down when someone clicks that cell and starts typing instead of having to scroll through the list by hand?

TheAngryDrunk
Jan 31, 2003

"I don't know why I know that; I took four years of Spanish."
Not sure I understand the first question, but the answer to the second one is 'no.' You can stick a combo box on the worksheet and it will fill in the first item on the data validation list that starts with the same letter, but you can't do it with a cell.

GerbilNut
Dec 30, 2004

TheAngryDrunk posted:

Not sure I understand the first question, but the answer to the second one is 'no.' You can stick a combo box on the worksheet and it will fill in the first item on the data validation list that starts with the same letter, but you can't do it with a cell.

Didn't think so :( Oh well.

In response to the second, here are some screen shots to hopefully help explain.

When you select one item to filter by, it shows the item in the list like in this picture:




When you select multiple items to filter by, it shows (Multiple Items) We then have to manually type in the following row those items. I'd like to avoid them having to type those in and have it print out the selected filter items somewhere.

TheAngryDrunk
Jan 31, 2003

"I don't know why I know that; I took four years of Spanish."
I don't know if you can do that easily. You may be able to access the filter criteria via VBA and display it on the sheet.

Sub Par
Jul 18, 2001


Dinosaur Gum
Quick and dirty solution in VBA. Create a module, create this sub:

code:
Sub GetSelectedFilterItems(strPivotName As String, strPivotField As String)

Dim strReturn As String
strReturn = "Timesheets: "

For Each Item In ActiveSheet.PivotTables(strPivotName).PivotFields(strPivotField).PivotItems
    If Item.Visible = True Then strReturn = strReturn & Item.Name & ", "
Next Item

strReturn = Left(strReturn, Len(strReturn) - 2)

Sheets("Sheet2").Cells(2, 1).Value = strReturn

End Sub
Then add this to the worksheet that has the pivot table on it:
code:
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
GetSelectedFilterItems "pivottable1", "col3"
End Sub
Substitute "pivottable1" for the name of your pivot table (edit: you could also just do target.name) and "col3" for the name of the field you want to filter on (looks like "Timesheet Number" in your screenshot). This will dump the selected items into a comma-separated list into cell A2 of whatever sheet the pivot table is on. Adjust as needed. Results:

Sub Par fucked around with this message at 16:37 on Nov 3, 2010

GerbilNut
Dec 30, 2004

Sub Par posted:

Quick and dirty solution in VBA. Create a module, create this sub:



Sub Par, thanks for that, it does what I need but has a small quirk. It's pulling in random Timesheets that were used previously for testing, but that is no longer listed anywhere in the work book. See the picture for the filter items available and what it's printing.



Is there a way to clear those out somehow?

Sub Par
Jul 18, 2001


Dinosaur Gum
Did you refresh the pivot after clearing the data out of the workbook?

Nebel
Sep 30, 2002

Soiled Meat
For my job I'm taking a bunch of words written in a phonetic alphabet, and converting them to another phonetic alphabet. Essentially this is the same as transliteration.

First, I looked for some sort of transliteration module or such, but they're all preset for Latin<->Cyrillic and aren't customizable in the least.

Second, I found some selection.replace macros for Excel, which do what I need except for one thing, I'm dealing with unicode phonetic symbols.

For example:
code:
    Selection.Replace What:=ChrW(&H19B), Replacement:=ChrW(&H29F), LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=True
This works well, until I need to use a sequence of characters as input and/or output. The problem is I have no idea how to get Excel to accept a sequence of two ChrW(&Hxxx).

What I need this code to do, it take something like "tɬ" as input, and output "ʟ̣"

I could normally just use the Find/Replace window but I need to do this with 100 separate worksheets.

Alternatively if there was some sort of easier way to accomplish this, that would be great too!

gwar3k1
Jan 10, 2005

Someday soon

IceHawk posted:

For example:
code:
    Selection.Replace What:=ChrW(&H19B), Replacement:=ChrW(&H29F), LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=True
This works well, until I need to use a sequence of characters as input and/or output. The problem is I have no idea how to get Excel to accept a sequence of two ChrW(&Hxxx).

What I need this code to do, it take something like "tɬ" as input, and output "ʟ̣"

Does simple concatenation work: "ChrW(&Hxxx) & ChrW(&Hxxx)"

code:
    sFind = ChrW(&H19B) & ChrW(&H20B)
    sReplace = ChrW(&H29F) & "t"
    Selection.Replace What:=sFind, Replacement:=sReplace, LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=True
If it does, setup a sheet with two columns: Lang A, Lang B and enter your translations as needed, then use the following macro (or a modified version) to translate your sheets:

code:
Sub TranslateIt
  For i = 1 to Sheets.Count
    If Sheets(i).Name <> "TransLookUp" Then
      Sheets(i).Select
      iRow = 1
      Do While Sheets("TransLookup").Cells(iRow, 1) <> ""
        sFind = Sheets("TransLookup").Cells(iRow, 1)
        sReplace = Sheets("TransLookup").Cells(iRow, 2)
        Selection.Replace What:=sFind, Replacement:=sReplace, LookAt:=xlPart, _ 
             SearchOrder:=xlByRows, MatchCase:=True
        iRow = iRow + 1
      Loop      
    End if
  Next
End Sub

gwar3k1 fucked around with this message at 19:57 on Nov 3, 2010

Nebel
Sep 30, 2002

Soiled Meat

gwar3k1 posted:

Does simple concatenation work: "ChrW(&Hxxx) & ChrW(&Hxxx)"

code:
    sFind = ChrW(&H19B) & ChrW(&H20B)
    sReplace = ChrW(&H29F) & "t"
    Selection.Replace What:=sFind, Replacement:=sReplace, LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=True
If it does, setup a sheet with two columns: Lang A, Lang B and enter your translations as needed, then use the following macro (or a modified version) to translate your sheets:

code:
Sub TranslateIt
  For i = 1 to Sheets.Count
    If Sheets(i).Name <> "TransLookUp" Then
      Sheets(i).Select
      iRow = 1
      Do While Sheets("TransLookup").Cells(iRow, 1) <> ""
        sFind = Sheets("TransLookup").Cells(iRow, 1)
        sReplace = Sheets("TransLookup").Cells(iRow, 2)
        Selection.Replace What:=sFind, Replacement:=sReplace, LookAt:=xlPart, _ 
             SearchOrder:=xlByRows, MatchCase:=True
        iRow = iRow + 1
      Loop      
    End if
  Next
End Sub

Excellent.

code:
   sFind = ChrW(&HF111)
    sReplace = ChrW(&H29F) & ChrW(&H323)
    Selection.Replace What:=sFind, Replacement:=sReplace, LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=True
Worked fantastic.

Except I don't quite understand what your second macro does (I'm a Linguist and all I have is one year of computer science under my belt), all of my data is formatted so that column C contains the empty fields that I need to put the translation into, and column E contains the source.

gwar3k1
Jan 10, 2005

Someday soon

IceHawk posted:

Except I don't quite understand what your second macro does (I'm a Linguist and all I have is one year of computer science under my belt), all of my data is formatted so that column C contains the empty fields that I need to put the translation into, and column E contains the source.

Sorry, the macro assumes you have a sheet named "TransLookup". On that sheet you have a column (A) which contains your original characters, and a second column (B) which contains the characters that col A should be changed to. I'm assuming your task is as simple as "change xx to yy" without any conditions (i.e. not accounting for "change xx to yy but if xx preceeds xxz then change it to ccc").

The macro loops all the worksheets in your book that aren't TransLookup (which it is using as reference) then it is making the replacement for every replacement you have instructed it to do (all rows on TransLookup).

Does that make sense?

Nebel
Sep 30, 2002

Soiled Meat

gwar3k1 posted:

Sorry, the macro assumes you have a sheet named "TransLookup". On that sheet you have a column (A) which contains your original characters, and a second column (B) which contains the characters that col A should be changed to. I'm assuming your task is as simple as "change xx to yy" without any conditions (i.e. not accounting for "change xx to yy but if xx preceeds xxz then change it to ccc").

The macro loops all the worksheets in your book that aren't TransLookup (which it is using as reference) then it is making the replacement for every replacement you have instructed it to do (all rows on TransLookup).

Does that make sense?

Yeah that does, thank you very much. And it greatly simplifies matters!

GerbilNut
Dec 30, 2004

Sub Par posted:

Did you refresh the pivot after clearing the data out of the workbook?

I did fresh it but that didn't help. After some screwing around with it this morning I tracked down the problem. Under the Pivot Table Options, and the Data tab there is a drop down for "Number of Items to retain per field: Automatic" I changed that to None and it updates correctly now.

Thanks for all of the help, this sheet will now work wonders for us.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
What is the best way to check for matching cells in a range using VBA?

Example: I have a range of 10 cells, I want to check all 10 cells to see if any are the same.

e. Actually, I'm just going to post what I'm trying to do because I don't have a clue on how I'm going to accomplish this.

I have a table like so:



I want a msgbox to display if more than 1 cells in column B are "yes" AND the cells in column A (within the same rows of those cells in B that are "yes") are different dates.

Nothing needs to happen if the dates are the same and nothing needs to happen if the cells in B are "no"

This should be pretty easy but I have no idea how to do this.

e2.
So I think I may have an idea how to do this but I'm not sure on the syntax if someone could help me with this.

code:
Private Sub Worksheet_Change(ByVal Target As Range)

For each cell in column B
   If cell.value = "yes" Then
      array += cell.address
   End If
End For

If count(array) > 1 Then
   For each item in array
      array2 += adjacent cell in column A
   End For
End If

If array2 has duplicates Then
   msgbox "Working?"
End If

End Sub
I'll probably just change the msgbox to a conditional formatted cell because I don't want the msgbox popping up every time a cell changes.

IT Guy fucked around with this message at 17:13 on Nov 4, 2010

gwar3k1
Jan 10, 2005

Someday soon
Here's a sub that'll do what you want (identify duplicate positive dates):

code:
Sub DupCheck()
  bDuplicate = False
  sDates = ""
  For Each xCell In Range("B:B")
    If xCell.Value = "yes" Then
      If InStr(1, sDates, Cells(xCell.Row, 1)) > 0 Then
        bDuplicate = True
      Else
        sDates = sDates & Cells(xCell.Row, 1) & ","
      End If
    End If
  Next

  'bDuplicate is then the variable you want to check
End Sub
If you're using Excel >= 2007, there is a duplicate removal feature, if that's what this is hoping to do?

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

gwar3k1 posted:

Here's a sub that'll do what you want (identify duplicate positive dates):

code:
Sub DupCheck()
  bDuplicate = False
  sDates = ""
  For Each xCell In Range("B:B")
    If xCell.Value = "yes" Then
      If InStr(1, sDates, Cells(xCell.Row, 1)) > 0 Then
        bDuplicate = True
      Else
        sDates = sDates & Cells(xCell.Row, 1) & ","
      End If
    End If
  Next

  'bDuplicate is then the variable you want to check
End Sub
If you're using Excel >= 2007, there is a duplicate removal feature, if that's what this is hoping to do?

Actually, I made a mistake, I need to check array2 to see if every value is the same or unique.

Will that still work?

After Googling around, it appears the FREQUENCY() function may do what I need, I just don't know how to use it properly.

gwar3k1
Jan 10, 2005

Someday soon

IT Guy posted:

Actually, I made a mistake, I need to check array2 to see if every value is the same or unique.

Will that still work?

After Googling around, it appears the FREQUENCY() function may do what I need, I just don't know how to use it properly.

No, the sub I posted will store a list of unique values and return true if there are any duplicates. You can validate by doing:

code:
if len(sDates) > 0 and bDuplicate = false then
  msgbox("All yes dates are unique")
else
  msgbox("At least one yes date is repeated")
end if
To use worksheet functions in VB code:

code:
  'Application.WorksheetFunction.<functionname>([params])
  Application.WorksheetFunction.Frequency(Range("B:B"),Array("yes"))
Reading the help for Frequency doesn't really help me understand what it does or how it does it exactly.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

gwar3k1 posted:

No, the sub I posted will store a list of unique values and return true if there are any duplicates. You can validate by doing:


Thanks for your help on this. I don't think I'm explaining the situation properly or maybe I'm being dumb and not understanding what is going on here. It is alright if the dates are duplicated but if there are more than 1 distinct values then that is the problem.

I'll try to clear this up a bit. I need to do this:
code:
For Each c As Range("B1:B10") 
    If c.Value = "Yes" And Range(c.Address).Offset(0, -1).Value Is Not Null Then
         'This is where I need to dump the adjacent cell's (column A) value into an array and don't know how
    End If 
Next 
 
 'This is where I need to check if the array has more than 1 distinct unique value and don't know how
Duplicates are fine, but more than 1 distinct is not.

IT Guy fucked around with this message at 13:50 on Nov 5, 2010

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Finally got it doing what I want.

Here is how I did it:

code:
Function inColl(value As Variant, coll As Collection)
    For Each v In coll
        If value = v Then
            inColl = True
        ElseIf value <> v Then
            inColl = False
        End If
    Next
End Function

Private Sub Worksheet_Change(ByVal target As Range)
        Dim coll As New Collection
        For Each c In Range("U4:U10")
            If c.value = "Yes" And Range(c.Address).Offset(0, -1).value <> "" And inColl(Range(c.Address).Offset(0, -1).value, coll) = False Then
                coll.Add Range(c.Address).Offset(0, -1).value
            End If
        Next
    
        If coll.Count > 1 And Range("L20").value = "" Then
            Range("L20").value = "Warning: Multiple dates in today's prepayment"
        ElseIf coll.Count <= 1 And Range("L20").value <> "" Then
            Range("L20").value = ""
        End If
End Sub

Zhentar
Sep 28, 2003

Brilliant Master Genius
I don't think inColl does what you think it does.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

Zhentar posted:

I don't think inColl does what you think it does.

I noticed that too.

How should I fix that?

So let's say I choose Nov3 in the first cell
inColl will return false because there is nothing in the collection.

I choose Nov4 in the second cell.
inColl returns false because Nov4 <> Nov3

I choose Nov 3 in the third cell. (here is the problem right?)
inColl will be assigned true when it sees Nov3 = Nov3 the first item in the collection, but then when it checks it against the next item in the collection it will return false because Nov3 <> Nov4

However, the sheet seems to be working so I'm confused again.

Is this what you were referring to?

IT Guy fucked around with this message at 18:31 on Nov 5, 2010

Zhentar
Sep 28, 2003

Brilliant Master Genius
Yeah.

You want to do something like this:
code:
Function inColl(value As Variant, coll As Collection)
    For Each v In coll
        If value = v Then
            inColl = True
            Exit Function
        End If
    Next
End Function
The Exit Function is just there for efficiency. It could also be an Exit For if you needed to do some processing at the end.

gwar3k1
Jan 10, 2005

Someday soon
I would have posted a modified version of my sub, but Zhentar's is much better.

Adbot
ADBOT LOVES YOU

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
Hey thanks, both of you.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply