Search code examples
excelvbamsgbox

Set part of string as percentage


Been trying to get a msgbox to show a range of cells that user can see and use. This needs to be a list from two columns in another sheet in my Workbook. Got the most of the code done, but I'm getting an output that I can't get my head around.

in the code I want the NCol to be shown as percentage when msgbox prompts.

First idea was to set each cell in that that variable to Format(NCol,"0.00%") after the For NCol = ....

Second idea was inside the Str & Rng.Cells...Format(Ncol.. which obviously didn't go as wanted.

Any pointers in the right direction is much appreciated. picture below shows outcome in msgbox. Input

Input and wanted output look

outcome

Outcome to msgbox

Sub ShowTopCat()
    Dim Rng As Range
    Dim ACell As Range
    Dim Str As String
    Dim ARow As Long
    Dim NCol As Long
    Dim art As Worksheet
    Set art = Worksheets("Sheet1")
    On Error Resume Next
    Set Rng = art.Range("x2:y101")
    If Rng Is Nothing Then Exit Sub
    On Error Resume Next
    For ARow = 1 To Rng.Rows.Count
        For NCol = 1 To Rng.Columns.Count
                Str = Str & Rng.Cells(ARow, NCol).Value & vbTab
        Next
        Str = Str & vbCrLf
    Next
    MsgBox Str, vbInformation, "You top cats"
End Sub

Solution

  • Why use two loops when your range is fixed?

    Sub ShowTopCat()
        Dim art As Worksheet
        Dim Rng As Range
        Dim Str As String
        Dim ARow As Long
    
        Set art = Worksheets("Sheet1")
    
        On Error Resume Next
        Set Rng = art.Range("x2:y101")
        If Rng Is Nothing Then Exit Sub
        On Error Resume Next
    
        For ARow = 1 To Rng.Rows.Count
            With Rng.Cells(ARow, 1)
                If .Value2 <> vbNullString Then
                    Str = Str & .Value2 & vbTab & Format(.Offset(0, 1).Value2, "0" & Application.DecimalSeparator & "00%")
                    Str = Str & vbCrLf
                End If
            End With
        Next ARow
        MsgBox Str, vbInformation, "You top cats"
    End Sub