简体   繁体   English

在工作簿打开时运行的excel宏,不使用公式更新单元格

[英]excel macro, that runs when workbook opens, doesnt update cell with formula

Scenario : Need to create an excel that fetches data from multiple sources and concatenate text into a few cell so as to be used as part of report. 场景 :需要创建一个Excel,该Excel从多个源中获取数据并将文本连接到几个单元格中,以便用作报表的一部分。

Goal : To have better formatting of the final output cell. 目标 :更好地格式化最终输出单元格。 More precisely, want to get few keywords of output cells to be made bold. 更确切地说,要使输出单元格的关键字少一些就加粗。

Method used : (simplified here for keeping it precise) Single sheet workbook. 使用的方法 :(此处为了精确起见,已简化)单页工作簿。

Cell A1 = "Output from DataSource1 contains keyword1 "
Cell A2 = "Output from DataSource2 contains keyword2" 
Cell A3 = "=CONCATENATE(A1, A2)"
Cell A4 = "Output from DataSource1 contains keyword1 Output from DataSource2 contains 

keyword2" (The actual text that is populated in A3) keyword2“(在A3中填充的实际文本)

Press AltF11 and add the following code in 'ThisWorkbook' 按AltF11,然后在“ ThisWorkbook”中添加以下代码


Sub Workbook_Open()
Dim i, l As Integer
Dim Keywords(1 To 2) As String
Dim N As Long

Keywords(1) = "keyword1"
Keywords(2) = "keyword2"

For N = LBound(Keywords) To UBound(Keywords)
    i = InStr(1, Range("A3"), Keywords(N), vbTextCompare)
    l = Len(Keywords(N))
    If i > 0 Then
        With Range("A3").Characters(Start:=i, Length:=l).Font
            .FontStyle = "Bold"
        End With
    End If
Next N

For N = LBound(Keywords) To UBound(Keywords)
    i = InStr(1, Range("A4"), Keywords(N), vbTextCompare)
    l = Len(Keywords(N))
    If i > 0 Then
        With Range("A4").Characters(Start:=i, Length:=l).Font
            .FontStyle = "Bold"
        End With
    End If
Next N

End Sub

Observation : Keywords in Cell A4(simple text) get bold. 观察结果 :单元格A4中的关键字(纯文本)变粗体。 Keywords in Cell A3 do not get bold. 单元格A3中的关键字不会变粗体。

Expected : Keywords in Cell A3 should get bold. 预期 :单元格A3中的关键字应加粗。 That is the main requirement. 这是主要要求。

Question : (1) Is it possible to get few keywords of a cell be marked as bold when the cell content is coming from a formula (lets say a concatenation of two other cells)? 问题 :(1)当一个单元格的内容来自一个公式(比如说两个其他单元格的串联)时,是否有可能使一个单元格的关键词被标记为粗体? (2) Is it possible to run such a code/macro when workbook opens? (2)打开工作簿时是否可以运行这样的代码/宏?

看看这种解决方法(如何格式化串联的单元格):http: //youtu.be/Sxwyp-pUxBk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM