使用其他单元格中的值填充单元格中文本中的多个空白

问题描述 投票:0回答:1

我正在使用 Excel VBA 自动执行以下任务。

在单元格 D2 中,我有以下换行文本:

“我的名字是C2,我来自C3,我喜欢阅读A3类型的书籍。我最喜欢的运动是B6。”

此处,名称、位置、书籍类型和最喜欢的运动来自单元格 C2、C3、A3 和 B6。

我可以通过VBA进行单元格到单元格的复制粘贴,但无法实现上述任务。困难在于使用同一工作表中的其他单元格值填充文本单元格中的多个位置/空白。

我该如何解决这个问题?

使用VBA通过引用其他单元格来填充单元格中的多个指定位置。

excel vba reference
1个回答
0
投票
  • &
  • 连接字符串
Sub Demo1()
    Range("D2").Value = "My name is " & Range("C2") & _
        " , I am from " & Range("C3") & ", i love reading " & _
        Range("A3") & " type of books. My favorite sport is " & _
        Range("B6") & "."
End Sub

  • 使用
    Replace
    功能
Sub Demo2()
    Dim sTxt As String, aRef, i As Long
    Const CELL_REF = "C2 C3 A3 B6"
    sTxt = "My name is CELL0 , I am from CELL1, i love reading CELL2 type of books. My favorite sport is CELL3."
    aRef = Split(CELL_REF)
    For i = 0 To UBound(aRef)
        sTxt = Replace(sTxt, "CELL" & i, Range(aRef(i)).Value)
    Next
    Range("D2").Value = sTxt
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.