Excel / VBA:字符串

时间:2016-05-02 09:28:54

标签: excel excel-vba vba

所以我有如下的大字符串:

bread 54,23424%, butter 15,521424%, chocolate 0,02142%

输出应为

bread 54%, butter 16%, chocolate

需要将它们经济地舍入到2整数点。 很长一段时间我得到了一个搜索我需要修剪的部分的函数,但我需要得到一个回合。

Th函数接受

之类的参数

regExchange(;" reg.Sattern&#34 ;;"替换模式")

这么长的功能是:

    Function regExchange(MyRange As Range, strPattern As String, strReplace As String) As String
    Dim regEx As New RegExp
    Dim strInput As String

    If strPattern <> "" Then
        strInput = MyRange.Value

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.Test(strInput) Then
            regExchange = regEx.Replace(strInput, strReplace)
        Else
            regExchange = "Muster nicht gefunden"
        End If
    End If
End Function

PS:模式可能包含多于或少于这三个对象,我将其作为字符串获取,如上所述。

2 个答案:

答案 0 :(得分:0)

使用以下内容,假设范围是K22

class Movie
{
    string brand;
    public string BRAND
    {
        get{ return brand;}
    }
    List<Dvd> films = new List<Dvd>();
    public Movie(String brand)
    {
       this.brand = brand;  
    }
}

class DVD
{
     public int BARCODE{get;set}
     public Availability STATUS{ get;set;}
     public DateTime RENTALDATE { get; set; }
     public DateTime RENTALDUE { get; set; }
     public DVD(int barcode, Availability avail, DateTime out, DateTime in){
          this.BARCODE = barcode; this.STATUS = avail; this.RENTALDATE = out; this.RENTALDUE = in;
     }
}

class Store
{
    List<Movie> films = new List<Movie>();
    public void addFilmtoStore(-----all params from dvd & movie classes----);
}

答案 1 :(得分:0)

使用split是解析这样的字符串的好方法。也许拆分空白是一种更好的方法来解析值并将它们四舍五入到所需的结果:

Function Round_Numbers(Text As String) As String
Dim Arr, I As Integer, pos As Integer
    Arr = Split(Text, " ")
    For I = LBound(Arr) To UBound(Arr)
        pos = InStrRev(Arr(I), "%")
        If pos > 0 Then
            Arr(I) = Round(Val(Replace(Left(Arr(I), pos - 1), ",", ".")), 0) & "%" & IIf(I < UBound(Arr), ",", "")
        End If

    Next I
Round_Numbers = Join(Arr, " ")
End Function
相关问题