【问题标题】:Find and Replace number text to fraction text查找数字文本并将其替换为分数文本
【发布时间】:2021-08-14 05:43:37
【问题描述】:

我有两张桌子。

Droplist Table 有 2 列:

  • [HeaderA] 包含查找值

  • [HeaderA_D] 包含替换值

HeaderA HeaderA_D
1 1/50
2 1/100
3 1/200
4 1/500

表 1 表

  • [HeaderB] 是我尝试从 Droplist[HeaderA] 中查找匹配值并替换为 Droplist[HeaderA_D] 的列
HeaderB
1
2
3
4

当前结果

HeaderB
18624
1/100
1/200
1/500

预期结果

HeaderB
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

'''

【问题讨论】:

    标签: vba replace format find


    【解决方案1】:

    我再次在 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
    

    【讨论】:

    • 感谢建祥,但这不是问题所在。我的问题是运行代码,当我尝试查找“1”并替换为“1/50”时,Table1[HeaderB] 没有返回正确的值
    • 是的,我知道问题出在文本 1/50 上,可以通过先更改格式然后更新值来解决,稍后让我告诉您解决方案。
    • 你可以查看我编辑的答案,它现在解决了问题:)
    • 我猜我的表有点误导。 Table1[HeaderB] 有很多行。我只是使用 1,2,3,4 作为演示。它可能是 1,1,3,4,1,2,3,4,4。我不知道哪一行将包含值“1”
    • 是的,可以通过在替换功能中执行循环来实现,请参阅我编辑的答案并接受如果帮助:)
    猜你喜欢
    • 2011-03-22
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2012-12-10
    • 2015-07-07
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多