Question

VBA Syntax

Asked by: Debsyl99

Hi
I have the following code that checks a range on a spreadsheet and copies the value into a specific cell in another range. This works fine except if I run it more than once. What I need to do is first set the value of O to "" for each cell in the range Results. The range PTable is also very long as it can have a variable number of values in the range. I need the function to stop when it reaches a value on Ptable that's empty ie "".

Sub EnterRisk()
    Dim O As Range
    For Each cell In Range("PTable")
        P = cell
        I = cell.Offset(0, 1)
        R = cell.Offset(0, -2)
        Set O = WorksheetFunction.Index(Range("Results"), 7 - I, P)
        If O = "" Then
            O = R
        Else
            O = O & "," & R
        End If
    Next cell
End Sub

I've managed to set the value of each cell in the Range results to "" by using the following code - but it looks clunky

Sub EnterRisk()
    Dim O As Range
    For Each cell In Range("PTable3")
        P = cell
        I = cell.Offset(0, 1)
        R = cell.Offset(0, -2)
        Set O = WorksheetFunction.Index(Range("Results"), 7 - I, P)
        O = ""
        Next cell
        For Each cell In Range("PTable3")
        P = cell
        I = cell.Offset(0, 1)
        R = cell.Offset(0, -2)
        Set O = WorksheetFunction.Index(Range("Results"), 7 - I, P)
        If O = "" Then
            O = R
        Else
            O = O & "," & R
        End If
    Next cell
End Sub

However I'm not having any luck with the syntax to check the value of of p and only execute the code to assign value to O if P is <>"". I also need to run this code across two different worksheets - at the moment it runs off the same worksheet. So -  the ranges "Range" and "PTable" will be on separate worksheets.

Can someone help? I hope I've explained that clearly enough.
Thanks
Deb

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-09-18 at 04:34:49ID21993098
Tags

vba

,

syntax

Topic

Microsoft Excel Spreadsheet Software

Participating Experts
1
Points
500
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Lock a cell in Excel without protecting worksheet
    Hello all. We have a need to lock a cell or cells in a worklsheet without password protecting the entire worksheet/workbook. Many people will be using this spreadsheet and to try and coordinate passwords with everyone would be a real PIA. Is this possible with Excel 97 or 200...
  2. VBA syntax for placing a value from Access table into an E…
    Hello ~ I wouyld like to refrence a value (or several values) in an Access table (using a DLookup, if possible) and place that value in a specific cell (A1) in an Excel Spreadsheet. I am already using Microsoft Query to place a data into the formatted spreadsheet and would ...
  3. Using Variable in VBA to Subsitiute Worksheet and Range
    Tyring to use a variable in VBA to subsitiute a worksheet/range value in excel. Cell J25 contains worksheet ref 'Match Results' Cell J25 contains cell ref R5C13 VBA code includes Dim ref1 As String Dim ref2 As String ref1 = Range("I25").Value ref2 = Range("...
  4. How to populate cells in spreadsheet from cells from anoth…
    I have a spreadsheet that I need to populate some cells with from cells in another spreadsheet. I need to write some VBA Code that will loop through the second spreadsheet and take those values and populate them in specific cells in the main spreadsheet. Hope this makes sen...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ManAlivePosted on 2006-09-18 at 04:46:30ID: 17542513


As a starting point I'd define each variable in the way variable "O" has been, implicit definition can only lead to problems. In the same way, rather than specifying "Cell.offset(0,1)", I'd be far more inclined to have this as "Cell.Offset(0,1).Range", again for clarity and to avoid confusion.



 

by: ManAlivePosted on 2006-09-18 at 04:47:11ID: 17542524


In your case it would be ".Value" and not ".Range" of course, since you wish to refer to the actual value.



 

by: Debsyl99Posted on 2006-09-18 at 04:55:30ID: 17542588

Thanks - but please assume I'm an idiot with vba - I've already had help with this here
http://www.experts-exchange.com/Applications/MS_Office/Excel/Q_21989474.html

 

by: ManAlivePosted on 2006-09-18 at 05:15:15ID: 17542748



Try this. Let me know if it works alright. This will clear everything out of range "Results" at first though, so make sure you do want it all cleared.


Sub EnterRisk()
    Dim O As Range
    Dim cell as Range
    Dim P as Long
    Dim I as Long
    Dim R as Range

    Range("Results").ClearContents
    For Each cell In Range("PTable3")
        P = cell.Value
        I = cell.Offset(0, 1).Value
        R = cell.Offset(0, -2).Range
        Set O = WorksheetFunction.Index(Range("Results"), 7 - I, P)
        If O.Value = "" Then
            O.Value = R.Value
        Else
            O.Value = O.Value & "," & R.Value
        End If
    Next cell
End Sub

 

by: Debsyl99Posted on 2006-09-18 at 05:19:32ID: 17542770

Thanks - it's flashing up error "argument not optional " on .range in

R = cell.Offset(0, -2).Range

 

by: ManAlivePosted on 2006-09-18 at 05:28:30ID: 17542841



Oops! If at first you don't succeed! Try this.


Sub EnterRisk()
    Dim O As Range
    Dim cell as Range
    Dim P as Long
    Dim I as Long
    Dim R as Range

    Range("Results").ClearContents
    For Each cell In Range("PTable3")
        P = cell.Value
        I = cell.Offset(0, 1).Value
        R = cell.Offset(0, -2)
        Set O = WorksheetFunction.Index(Range("Results"), 7 - I, P)
        If O.Value = "" Then
            O.Value = R.Value
        Else
            O.Value = O.Value & "," & R.Value
        End If
    Next cell
End Sub

 

by: Debsyl99Posted on 2006-09-18 at 05:40:04ID: 17542919

Hi
No it's still not playing - Just returns " Object Variable or With Block variable not set". The code I posted works fine, it just returns a 400 error if not every cell in the range PTable3 contains a value so really I just need to fix this. As I also said - I need the code to reference the range Ptable3 on Worksheet2 when the range "Results" is on worksheet1
Thanks

 

by: ManAlivePosted on 2006-09-18 at 06:12:51ID: 17543153



This should work at last. You'll need to set "Results" to just reference the coloured cells and not include the headings, otherwise you'll lose the headings, and also it won't put it in the right place. The naming of the range should already take care of the fact it's on another worksheet. This all assumes too that range "PTable3" is the single probability column.

Sub EnterRisk()

    Dim O As Range
    Dim cell As Range
    Dim P As Range
    Dim I As Range
    Dim R As Range

    Range("Results").ClearContents
    For Each cell In Range("PTable3")
        Set P = cell
        Set I = cell.Offset(0, 1)
        Set R = cell.Offset(0, -2)
        If P.Value <> "" and I.Value <> "" Then
       
        Set O = Range("Results").Offset(6 - I.Value, P.Value - 1)

         If O.Value = "" Then
            O.Value = R.Value
        Else
            O.Value = O.Value & "," & R.Value
        End If

        End If

    Next cell

End Sub


 

by: Debsyl99Posted on 2006-09-18 at 06:20:21ID: 17543212

Hi
All the conditions you mentioned are met. However it's still not quite right as I'm getting
Data type mismatch on
O.Value = R.Value

 

by: ManAlivePosted on 2006-09-18 at 06:39:46ID: 17543382



Tested this one to death, if this doesn't work I'm shooting myself.



Sub EnterRisk()

    Dim O As Range
    Dim cell As Range
    Dim P As Range
    Dim I As Range
    Dim R As Range

    Range("Results").ClearContents
    For Each cell In Range("PTable3")
        Set P = cell
        Set I = cell.Offset(0, 1)
        Set R = cell.Offset(0, -2)
        If P.Value <> "" And I.Value <> "" Then
       
        Set O = Range("Results").Cells(1, 1).Offset(6 - I.Value, P.Value - 1)

         If O.Value = "" Then
            O.Value = R.Value
        Else
            O.Value = O.Value & "," & R.Value
        End If

        End If

    Next cell

End Sub

 

by: Debsyl99Posted on 2006-09-18 at 07:05:28ID: 17543574

Thanks - that's working great now. Just one more question if that's ok - how do I get this macro to run automatically when the sheet opens?

 

by: ManAlivePosted on 2006-09-18 at 07:11:11ID: 17543623


When the workbook opens or when the sheet is selected?

 

by: Debsyl99Posted on 2006-09-18 at 07:13:25ID: 17543641

sorry - when the workbook opens

 

by: ManAlivePosted on 2006-09-18 at 07:14:19ID: 17543651


To get it run when the workbook is opened, put the below code into the "ThisWorkbook" section of you VBA project, not in the Modules.


Private Sub Workbook_Open()

    Dim O As Range
    Dim cell As Range
    Dim P As Range
    Dim I As Range
    Dim R As Range

    Range("Results").ClearContents
    For Each cell In Range("PTable3")
        Set P = cell
        Set I = cell.Offset(0, 1)
        Set R = cell.Offset(0, -2)
        If P.Value <> "" And I.Value <> "" Then
       
        Set O = Range("Results").Cells(1, 1).Offset(6 - I.Value, P.Value - 1)

         If O.Value = "" Then
            O.Value = R.Value
        Else
            O.Value = O.Value & "," & R.Value
        End If

        End If

    Next cell

End Sub

 

by: Debsyl99Posted on 2006-09-18 at 07:34:11ID: 17543791

Thanks - this is running off a query to an access database that automatically updates the data when the sheet loads. When the macro runs when the workbook opens it's just returning a set of blank cells - the data refresh and the running of this code are out of sink maybe - which as I've spent ages trying to get this sorted and it's so close - is really annoying. I know it's pushing the remit of this question slightly - butI'm not far off shooting myself either - this is being a massive pain. The trouble is that two sheets need to open in separate windows - like a split view as the format varies on these sheets - otherwise I'd run it all on one sheet. Any ideas before I close this out?
Thanks again
Deb

 

by: ManAlivePosted on 2006-09-18 at 07:38:33ID: 17543836


How is the data refresh running, where is that triggered?

 

by: Debsyl99Posted on 2006-09-18 at 07:53:30ID: 17543950

It's just set on the external data range properties - refresh data on file open on worksheet

 

by: ManAlivePosted on 2006-09-18 at 08:02:05ID: 17544038


You could have the macro above run from clicking a button instead, would that be satisfactory?

 

by: Debsyl99Posted on 2006-09-18 at 08:04:20ID: 17544064

Yes - that'd be great thanks - is that toolbar button or can you get one on the worksheet itself?

 

by: ManAlivePosted on 2006-09-18 at 08:12:49ID: 17544144


One on the worksheet itself.

Goto View - Toolbars - Control Toolbox within Excel on the sheet you want the button. Click on Command Button and then click where you want the button to be. Right click on the button and select Properties. Then change the "Caption" property to whatever you want the button to say on it (You can also rename the button if you wish). Double click the button and between the sub declaration and "End Sub" put:

EnterRisk


You'll need to make sure the code is back in the Module and not in the ThisWorkbook section now, make sure it's the one headed "Sub EnterRisk()"

Back in Excel click the "Exit Design Mode" on the Control Toolbox bar and save, and you should be good to go!

 

by: Debsyl99Posted on 2006-09-18 at 08:29:15ID: 17544286

That's great - here are your well-deserved points. You've been a star - thanks very much!
Deb :))

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...