将字符串的一部分设置为百分比

时间:2019-10-11 08:20:12

标签: excel vba msgbox

试图获取一个msgbox来显示用户可以看到和使用的一系列单元格。这需要是我的工作簿中另一张工作表中两列的列表。完成了大部分代码,但是我得到的输出无法理解。

在代码中,我希望NCol在msgbox提示时显示为百分比。

第一个想法是在Format(NCol,"0.00%")之后将该变量中的每个单元格设置为For NCol = ...

第二个想法显然不在Str & Rng.Cells...Format(Ncol..之内。

任何朝着正确方向的指针都值得赞赏。下图显示了msgbox中的结果。 输入

Input and wanted output look

结果

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

1 个答案:

答案 0 :(得分:2)

为什么您的范围是固定的,为什么要使用两个循环?

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