首页 > 解决方案 > 查找数字文本并将其替换为分数文本

问题描述

我有两张桌子。

Droplist 表有 2 列:

标头A 标头A_D
1 1/50
2 1/100
3 1/200
4 1/500

表 1 表

标头B
1
2
3
4

当前结果

标头B
18624
1/100
1/200
1/500

预期成绩

标头B
1/50
1/100
1/200
1/500

问题:

我很难找到“1”并将其替换为“1/50”。它不断将其替换为 18624,即 1950 年 1 月 1 日,数字格式为“日期”

我试过了:

我的代码在下面,我确保两者都在 .Numberformat = "Text"

'''

Sub Find_Replace()

Dim b, c As Variant

Dim j As Integer

Set b = Range("Droplist[HeaderA]")

Set c = Range("Droplist[HeaderA_D]")

    For j = 1 To Application.WorksheetFunction.CountIf(Range("Droplist[HeaderA]"), "<>")
    
        Range("Table1[HeaderB]").Select
        Range("Table1[HeaderB]").NumberFormat = "@"
        
        Application.ReplaceFormat.NumberFormat = "@"
        Selection.Replace What:=b(j), Replacement:=c(j), LookAt:=xlWhole, _
            SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
            ReplaceFormat:=True
        
    Next j

End Sub

'''

标签: vbareplaceformatfind

解决方案


我再次在 VBA 上重新执行了您的问题,当我将原始数据更改为文本 1/50 并连续执行 VBA 代码时,同样的问题再次发生在我的 excel 上。我认为这个问题是由excel中的函数引起的find and replace,为了解决它,最好使用replace函数,这是解决方案,如果有帮助,请接受:)

我的原始数据

在此处输入图像描述

具有替换功能的 VBA 代码:

Sub Find_Replace()

Dim b, c As Variant
Dim replaceValue As String
Dim j As Integer
Dim lastrow As Long, headerLastrow As Long, replaceTime As Long

headerLastrow = Sheet1.Range("A1").End(xlDown).Row
lastrow = Sheet1.UsedRange.Rows.Count

Set b = Sheet1.Range("A1", "A" & lastrow)
Set c = Sheet1.Range("B1", "B" & lastrow)

Sheet1.Range("E2", "E" & lastrow).NumberFormat = "@"

    For j = 1 To lastrow
            
        For replaceTime = 1 To headerLastrow
        replaceValue = c(replaceTime).Text
        Sheet1.Cells(j, 5).Value = Replace(Sheet1.Cells(j, 5).Value, b(replaceTime), replaceValue)
        Next
    Next j

End Sub

推荐阅读