Consulting

Results 1 to 3 of 3

Thread: For loop inside IF statement

  1. #1
    VBAX Newbie
    Joined
    Dec 2017
    Posts
    1
    Location

    For loop inside IF statement

    Hi guys,

    Never used VBA before and basically just trying write this sub:

    Sub Populate_Empties()
    Dim i As Integer
    Dim j As Integer
    Dim n As Integer
    Dim m As Integer
    Dim k As Integer
    ' test for 50 rows...then change i from 2 to 278970
    m = 2
    For k = 3 To 8
    For i = 2 To 50
    If (IsEmpty(Cells(i, k).Value)) Then
    m = i   'any statement
    Else
    j = i - 1
    For n = m To j
    Cells(n, k).Value = Cells(i, k).Value
    m = i + 1
    End If
    End Sub

    I keep getting error End If without Block

    Any suggestions?

  2. #2
    VBAX Expert Dave's Avatar
    Joined
    Mar 2005
    Posts
    835
    Location
    Please use code tags. You need to end For loops with a Next. Use option explicit at top of code and select Debug in the code window. Also, note the sheet name specification. HTH. Dave
    Option Explicit
    Sub Populate_Empties()
    Dim i As Integer, j As Integer, n As Integer, m As Integer, k As Integer
    ' test for 50 rows...then change i from 2 to 278970
    m = 2
    For k = 3 To 8
    For i = 2 To 50
    If (IsEmpty(Sheets("YourSheetName").Cells(i, k).Value)) Then
    m = i 'any statement
    Else
    j = i - 1
    For n = m To j
    Sheets("YourSheetName").Cells(n, k).Value = Sheets("YourSheetName").Cells(i, k).Value
    m = i + 1
    Next n
    End If
    Next i
    Next k
    End Sub

  3. #3
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,726
    Location
    1. I'd use Long instead of Integer since there are more rows that an Integer can address

    2. Just using Cells without some worksheet reference defaults to the Activesheet

    3. For performance, I'd use Application.ScreenUpdating = False


    I assume that this is just a learning exercise, since it didn't seem to do anything on my test
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •