Betty
Betty

Reputation: 11

How to link 2 sub procedures in VBA

I want to be able to use VBA code to:

  1. First highlight all the non-empty cell in a column
  2. Then replace those non-empty cells with two lines of content in one cell.

But when I run my code, only the function UseLineFeedCharacter is working, and it replaces all cells with the new content.

I don't know if it is because I didn't link those two sub procedures together or not. Thank you for helping out!!! My code is like this:

Sub UseLinefeedCharacter()
    Dim str  As String
    str = "Line 1" & vbLf & "Line 2" & vbLf & "Line 3"
    With [a1]
        .Value = str
        .Columns.AutoFit
        .Rows.AutoFit
    End With
End Sub

Sub qwerty()
Dim rng As Range, r As Range, rSel As Range

Set rng = Range("B2:C7")
Set rSel = Nothing

For Each r In rng
    If r.Value <> "" Then
        If rSel Is Nothing Then
            Set rSel = r
        Else
            Set rSel = Union(rSel, r)
        End If
    End If
Next r
If Not rSel Is Nothing Then rSel.Select
End Sub

Upvotes: 1

Views: 719

Answers (1)

K.Dᴀᴠɪs
K.Dᴀᴠɪs

Reputation: 10139

There are a few ways to accomplish this task.

You can create another routine that calls both procedures:

Sub Main
    UseLinefeedCharacter
    qwerty
End Sub

Which you will just run Main, or you can just call the other Sub from the first one.

Sub UseLinefeedCharacter()
    Dim str  As String
    str = "Line 1" & vbLf & "Line 2" & vbLf & "Line 3"
    With [a1]
        .Value = str
        .Columns.AutoFit
        .Rows.AutoFit
    End With
    qwerty      '<-- Called qwerty sub
End Sub

This obviously depends on the scope of each sub. If one is located in a different module and is a Private Sub, then this will not work.

Upvotes: 1

Related Questions