Using IF statement in VBA

I am writing some VBA code.  What I want to do is go through each row of a 
sheet and put a the formula =IF(R" & intRowNumber & " = "US", "D", "F").  
Basically I want it to check each cell in Column R to see if it is US if it 
is put a D in if not put in an F.  The code is below.

Private Sub DorF()

Dim intRowNumber As Integer
Dim strCountry As String

For intRowNumber = 2 To Rows.Count
    Range("brazil!W" & intRowNumber).Formula = ("=IF(R"& intRowNumber & " = 
"US", "D", "F")")
Next
    
End Sub

Obviously this doesn't work because of all of the quote marks.  How do I get 
around that.
0
DustinB (3)
6/13/2008 8:03:01 PM
excel 39879 articles. 2 followers. Follow

3 Replies
468 Views

Similar Articles

[PageSpeed] 24

It's pretty rare that someone wants to fill up all the cells in the column with
a formula.  Lots of times, the user wants to fill up until the last used row. 
(But this may not be what you really want.)

This code looks in column A to find the last used cell in that column and fills
up column W with your formula:

Option Explicit
Private Sub DorF()
    Dim intRowNumber As Long
    Dim LastRow As Long
    
    With Worksheets("Brazil")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        For intRowNumber = 2 To LastRow
            .Range("W" & intRowNumber).Formula _
                = "=IF(R" & intRowNumber & " =""US"",""D"",""F"")"
        Next intRowNumber
    End With
End Sub

But filling the formula cell by cell can take a pretty long time.

If you were doing this manually, you could select W2:W### and then type the
formula (for W2) and then hit ctrl-enter to fill all those selected cell with
the same formula.  Excel will adjust the references just like if you copied and
pasted it.

In code, it would look like:

Option Explicit
Private Sub DorF()
    Dim LastRow As Long
    
    With Worksheets("Brazil")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        .Range("W2:W" & LastRow).Formula = "=IF(R2=""US"",""D"",""F"")"
    End With
End Sub

The general tip for those quotation marks in your VBA code is to double them up.

Dustin B wrote:
> 
> I am writing some VBA code.  What I want to do is go through each row of a
> sheet and put a the formula =IF(R" & intRowNumber & " = "US", "D", "F").
> Basically I want it to check each cell in Column R to see if it is US if it
> is put a D in if not put in an F.  The code is below.
> 
> Private Sub DorF()
> 
> Dim intRowNumber As Integer
> Dim strCountry As String
> 
> For intRowNumber = 2 To Rows.Count
>     Range("brazil!W" & intRowNumber).Formula = ("=IF(R"& intRowNumber & " =
> "US", "D", "F")")
> Next
> 
> End Sub
> 
> Obviously this doesn't work because of all of the quote marks.  How do I get
> around that.

-- 

Dave Peterson
0
petersod (12004)
6/13/2008 8:29:07 PM
If your objective is to put the formula into the cell so it will 
automatically update when future changes are made in Column R, then this 
patch to the code statement inside the For-Next loop should work (note the 
doubling up of the **internal** quote marks)...

Range("brazil!W" & intRowNumber).Formula = ("=IF(R" & _
        intRowNumber & " => ""US"", ""D"", ""F"")")

Rick


"Dustin B" <DustinB@discussions.microsoft.com> wrote in message 
news:08213D96-B141-4B0E-8E6F-E97074A8C01C@microsoft.com...
>I am writing some VBA code.  What I want to do is go through each row of a
> sheet and put a the formula =IF(R" & intRowNumber & " = "US", "D", "F").
> Basically I want it to check each cell in Column R to see if it is US if 
> it
> is put a D in if not put in an F.  The code is below.
>
> Private Sub DorF()
>
> Dim intRowNumber As Integer
> Dim strCountry As String
>
> For intRowNumber = 2 To Rows.Count
>    Range("brazil!W" & intRowNumber).Formula = ("=IF(R"& intRowNumber & " =
> "US", "D", "F")")
> Next
>
> End Sub
>
> Obviously this doesn't work because of all of the quote marks.  How do I 
> get
> around that. 

0
6/13/2008 8:31:43 PM
Try this to just mark without a formula being left.

Sub markcellif1()
For i = 2 To Cells(Rows.Count, "r").End(xlUp).Row
If Len(Trim(Cells(i, "r"))) > 0 Then
Select Case UCase(Cells(i, "r"))
Case Is = "US": x = "D"
Case Else: x = "F"
End Select
Cells(i, "s") = x
End If
Next i
End Sub

-- 
Don Guillett
Microsoft MVP Excel
SalesAid Software
dguillett1@austin.rr.com
"Dustin B" <DustinB@discussions.microsoft.com> wrote in message 
news:08213D96-B141-4B0E-8E6F-E97074A8C01C@microsoft.com...
>I am writing some VBA code.  What I want to do is go through each row of a
> sheet and put a the formula =IF(R" & intRowNumber & " = "US", "D", "F").
> Basically I want it to check each cell in Column R to see if it is US if 
> it
> is put a D in if not put in an F.  The code is below.
>
> Private Sub DorF()
>
> Dim intRowNumber As Integer
> Dim strCountry As String
>
> For intRowNumber = 2 To Rows.Count
>    Range("brazil!W" & intRowNumber).Formula = ("=IF(R"& intRowNumber & " =
> "US", "D", "F")")
> Next
>
> End Sub
>
> Obviously this doesn't work because of all of the quote marks.  How do I 
> get
> around that. 

0
dguillett1 (2487)
6/13/2008 9:48:16 PM
Reply:

Similar Artilces:

HELP WITH VBA
I am trying to finish writing some simple program. My problem is that when I try and change the arguement from SELECTION CHANGE to CHANGE, it doesn't work. Can someone help? Private Sub Worksheet_Change(ByVal Target As Range) If Worksheets("Sheet3").Range("B3").Value = 2 Then Worksheets("Sheet1").Range("F3") = Worksheets("Sheet3").Range("F4").Value End Sub My second problem is that I would like my data rather than appearing in a cell, appear in a TEXT BOX. What do I do? Copying your exact same post from 3 days ago word...

Outlook using imap is receiving but not sending
Messages are being put in Sent folder and Send/Receive shows no errors but emails are not actually getting sent. This is a new install of Outlook on a new computer. Have I messed up the setup? "Theatre Girl" wrote in message news:64BB711F-FE56-440C-A850-DADCA8C3BA00@microsoft.com... > Messages are being put in Sent folder and Send/Receive shows no > errors but > emails are not actually getting sent. This is a new install of > Outlook on a > new computer. Have I messed up the setup? IMAP is not a sending protocol. It is used for receiving mails (out of your ...

Line charts using temperature and time factors
I want to create a line chart showing comparisons of heating and time. For example one item is held @ 30deg for 10secs then 100degs for 30secs while the comparison is plotted to show the difference. Help appreciated. try x-y scatter chart data-columnwise. Excelon_Ls <Excelon_Ls@discussions.microsoft.com> wrote in message news:6B9F5547-A35C-4272-9FDC-F2CE6122D783@microsoft.com... > I want to create a line chart showing comparisons of heating and time. For > example one item is held @ 30deg for 10secs then 100degs for 30secs while the > comparison is plotted to show the diff...

VBA: move to the next cell down from anywhere in the sheet
I am deleting rows based on a value in a column (< 16) and if the valu is 16 or greater I want to move down to the next row and check tha value and so on. i am using a Do Until value = "". What is the code for moving down to the next cell below ActiveCell -- jm ----------------------------------------------------------------------- jmp's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=2903 View this thread: http://www.excelforum.com/showthread.php?threadid=48770 Activecell.Offset(1,0).Select I would not recommend this though. If you want to dele...

HOW TO USE HYPERLINK within a droplist?
I have a question aabout this: eg. I set row A with validation list "yes/no", i want that if choose "yes", then open a word document named "checklist.doc". Instead of using a validation list, you could use a "yes" button and a "no" button. The yes button can be linked to a macro to open the word document. The no button can be linked to a macro the will type the text "Go to next step" or something like that. "Bonny" wrote: > I have a question aabout this: > eg. > I set row A with validation list "yes...

using forms
Vista Home Premium 32 / Outlook 2007 I have created some forms that used to work. No more. On selecting a form, I get "The form required to view this message cannot be displayed. Contact the administrator. To my knowledge, I am the administrator. This is a stand-alone PC in my residence. If I go to Manage User Accounts, it shows only 2 accounts - LastName Administrator and Guest. I have googled my problem and found references to FRMCACHE.DAT which I am told to delete and restart Outlook. Did that. Opened Outlook and tried to open a form. Same error. And FRMCACHE.DAT was not ...

Using Spanish on Publisher
I have copied and pasted a document in Spanish from Word to Publisher. Prompts keep coming up telling me that it cannot "hyphenate" this document. I'm guessing that it means since it's in another language it needs something to be able to spell-check, etc. I really don't care about checking the spelling, but the pop-ups keep interferring with my arranging the flyer I desperately need to get completed. It tells me to put in the disk and download the "hyphenate" feature. Can I download this from the net since I have no disks. Publisher came with my n...

I used Omsgclas.exe Utility and my contacts don't use then new form
I created a new form for contacts. I followed the three steps in the document How to Update Existing Items to Use a New Custom Form. I can click on Action and do new contact and the new form is used. I used Omsgclas.exe utility to change the message class of the contacts. It shows as changed. However, when I click on an old contact (previous to changing the form), A message form comes up (not the old contact form and not my new contact form). Anyone have any help how to get my new form pulled up for old messages? Note: I had a form with a ' in the name, I made a new form w...

FormulaR1C1 using variables
I want to do this but can't: ActiveCell.FormulaR1C1 = "=MyFunction(R[variable]C[variable])" What are my options? Try something like ActiveCell.FormulaR1C1 = _ "=MyFunction(R" & CStr(variable) & "C" & CStr(variable) & ")" Cordially, Chip Pearson Microsoft Most Valuable Professional, Excel, 1998 - 2010 Pearson Software Consulting, LLC www.cpearson.com On Wed, 21 Apr 2010 13:52:01 -0700, Cheah <Cheah@discussions.microsoft.com> wrote: >I want to do this but can't: > >ActiveCell.Fo...

Using lookup formula using more than one cell
I have a spreadsheet which lists clients by first name, last name, postcode and phone number - all in separate columns e.g. Andy Roberts M56 7HN 0161 428 3856 I have these all in one worksheets and in a named range called "Clients" On a separate worksheet (within the same workbook) I log all my enquiries. What I want to be able to do is type in to a cell the first name then in the next cell the last name and the following cells get populated with postcode and phone number based on BOTH of the first two cells by looking up the "Clients" range. I can get it...

Using XML with ASP.NET
I want to know where can I find Tutorials/Articles to learn implementing XML with asp.net. I am working on ASP.NET using C# from last one month. I have idea about XML but had not implemented yet with ASP.NET. Thanks in advance. Thanks Vinod Jajoo ...

Using secured OMA
Hi, Please help me with my misunderstanding. When I try ro connect by t68i or z600 (WAP 2.0) to OMA directly with SSL required, using mydomain.com/oma, of course, I get 403 error. When I use https://mydomain.com/oma I get "Couldn't reach the indicated web server." altough it works fine with Pocket PC. What's wrong? What should I configure to establish secured connection from mobile phone? Best regards, Vit Knyshevich. "Vit Knyshevich" <abuse_vit_knysh@hotmail.com> wrote: >Please help me with my misunderstanding. When I try ro connect by t68i or >z60...

Compile error using CTypedPtrList
Hi, I am having problems at compile time using the following line: CTypedPtrList<CPtrList, CString*> m_ClientList ; When compiled I get the following errors: emailcfgdlg.h(114) : error C2143: syntax error : missing ';' before '<' emailcfgdlg.h(114) : error C2501: 'CTypedPtrList' : missing storage-class or type specifiers emailcfgdlg.h(114) : error C2059: syntax error : '<' emailcfgdlg.h(114) : error C2238: unexpected token(s) preceding ';' I am using the version 6 of the compiler with SP5. Now I think this is something to do with the c...

Collecting Range Name values to VBA
I have a worksheet "Setup" where users type in a date in a cell named "ChtDte" and a path and database name in a cell named "FLName". I am using DOA to connect to a database and return a record set. The query used "qryCOCostwRates" uses a date paramater. Because this sheet will be used by several users all pointing to the database in different locations, I need to know where they have the database. I need to get the values in these two range names in the setup tab of the spreadsheet so I can connect to the data, and provide a value for ...

Using resources, how to ?
Hi guys, I am using MS Visual Studio 2005 Express ( yes, the one that u can download for free from MS website ) and I have a "little-big" problem with my program. First of all let me say that I created a simple console program, with his main and few functions, and I wish that my ..exe file can drop another .exe when launched. The other exe is another compiled program, and I wish to handle it from my main program as resource. There are some topics about handling resources, but I cannot find anything of good; I know how to use LoadResource, FindResource, etc, but both fail since I am...

scatter plots using pivot table data
In older versions of Excel, you could directly create xy scatter plots using pivot table data. In Excel 2000, the chart wizard says you can't use an xy scatter plot with pivot table data. Why????? Is there any way around this limitation? Dan - Don't tell the pivot table you're making a regular chart. Select a cell away from the PT and start the chart wizard. Select the XY Scatter type you want in step 1. In step 2, use the Series tab to select the ranges for the names, X values, and Y values of each series in your chart. Make sure you don't select one of the PT but...

Allow temporarily use of right click
I have made a databse in which I have disabled the right-click option. However, I have a form which opens reports, and I want to temporarily allow (only for the opened report) the right click option so the user can save and print the report. I have also no clue how to create a custom menu with only a few of the normal right-click options I hope my question is clear. Thanks -- Message posted via http://www.accessmonster.com "greeknl via AccessMonster.com" <u30909@uwe> wrote in message news:71abb764263d9@uwe... >I have made a databse in which I have disabled the right-c...

Need an IF statement....
I have a worksheet with a list in a column that gives choices .... is it possible to put an if statement somewhere within the sheet to make the choices picked in the column with the list change color? In other words if say in Column C your choices were yes, no, maybe, not at all can you put an if statment in say Column XX that says if the answer in c is yes then the font will show as bold red, if no the bold blue and so on...... format>conditional formatting>etc -- Don Guillett Microsoft MVP Excel SalesAid Software dguillett1@austin.rr.com "TechnoGram" <mumzee3@hotmail.c...

Using two pictures from clipart as my background
I can't seem to get more than one clipart as my background. When I try to add another one, it overrides the first one. I want two pictures, each on half the page, and faded. Thanks. On Jan 13, 7:31=A0pm, Michele <Mich...@discussions.microsoft.com> wrote: > I can't seem to get more than one clipart as my background. When I try to= add > another one, it overrides the first one. I want two pictures, each on hal= f > the page, and faded. Thanks. You can place multiple pictures on your slide (or slide master), but each slide can only contain one as it's ...

How to use interfaces
Hi ... How can you show in an UML diagram using visio that you have 1 class who uses the interface implementet by another ?? ex: C# public class MyClass : ImyInterface { //some code } //And then in another class you will do something like: private ImyInterface imi = new MyClass(); can you show this via UML shapes in Visio ?? thanks in advance ... -- ------------------------------- Med Venlig Hilsen Tonni Schm�cker Tonni@cool.dk ...

Using stationary when Word is used as the editor
Hello, I am having a problem with stationary when using word as the email editor. What is required is for a logo to be placed as a backgroun image in the top right hand corner. this works fine in outlook using this code: <HTML> <HEAD> <STYLE> BODY { font-family: Arial; font-size: 10pt; color: 000000; background-position: right top; background-repeat: no-repeat; background-image: url(Pic.jpg); } </STYLE> </HEAD> <BODY> </BODY> </HTML> However when Word is used as the email editor the background image is no longer placed in the top righ...

What do you use Excel for?
Just a general query really. Anybody willing to tell me what they use Excel for? Does anybody use it on a daily basis as part of the personal life? I'm not really looking for the reasons why people use it at the workplace, but why do people use it at home? Do you use it to manage your budgets etc???? Do you use it as a diary? Thanks in advance Excel is excellent for manipulating data. The uses are as wide as the imagination. There are people who use it to track the standings in a bowling league, others for managing a local golf tournament. One can build a loan calculator, kee...

using extended desktop mode
How can I move an Excel spreadsheet onto my second monitor. Word and Internet provide no problems, I just click & drag. Same way. You have to have the application window in a non-maximised state though, and you can then drag it from one to the other, or even size it so it spreads across the two screens completely. If I have the window maximised though, I am unable to drag it from screen to screen. -- Regards Ken....................... Microsoft MVP - Excel Sys Spec - Win XP Pro / XL 97/00/02/03 ------------------------------�-------------------------...

How do I used the outlook?
I don't know my microsoft exchange sever so I can't put in the right user name. What should I do? Version of Outlook? Close outlook. Go to control panel, mail and delete the current profile and make a new profile - Choose the correct account type - for most people its POP3, but could be IMAP. If you need more assistance with this we need to know the version of Outlook and who your email provider is. -- Diane Poremsky [MVP - Outlook] Outlook Tips: http://www.outlook-tips.net/ Outlook & Exchange Solutions Center: http://www.slipstick.com Outlook Tips by email: mailto:daily...

Chart using Macro
I have several sheets having similar data for different lanes. I have a macro which can create a graph I want with different series plotted in different forms for source data on a particular sheet. I want to be able to create a graph for the active sheet. How do I use ActiveSheet data as source data for the gaph. ...