目前,我有一个范围为rngP1
的模板。
其中包含以下文本:
“这是要确认 strTitle 已在 strCompany 的 strDate 上制定。”
基本上,我在另一个工作表中有一个数据,该数据将用于替换模板中的这3个字符串:
所以我想发生的是,在每一行数据中,它将搜索字符串 strTitle , strDate 和 strCompany 并替换它们根据每一行的数据。
我已经有一个代码,但是,它没有按我预期的那样工作:
Sub example()
Dim wsMain As Worksheet
Set wsMain = Sheets("Main")
Dim wsTemplate As Worksheet
Set wsTemplate = Sheets("Template")
Dim textToReplace As Variant
Dim array_example()
Dim Find_Text As Variant
Dim str As String
last_row = wsMain.Range("A1").End(xlDown).Row 'Last row of the data set
ReDim array_example(last_row - 1, 2)
Find_Text = Array("strTitle", "strDate", "strCompany")
str = wsTemplate.Range("rngP1").Value
'Storing values in the array
For i = 0 To last_row - 1
array_example(i, 0) = wsMain.Range("A" & i + 2)
array_example(i, 1) = wsMain.Range("C" & i + 2)
array_example(i, 2) = wsMain.Range("D" & i + 2)
Next
For i = LBound(array_example, 1) To UBound(array_example, 1)
For j = LBound(array_example, 2) To UBound(array_example, 2)
For a = 0 To UBound(Find_Text)
str = Replace(str, Find_Text(a), array_example(i, j))
Next a
Next j
MsgBox str
Next i
End Sub
错误的输出:
应为:
这是为了确认Title 1已于X公司于18年10月13日颁布。
下一行将是下一行title 2
。如此等等。
如果您有其他替代方法,我会很感激。
答案 0 :(得分:3)
这是一个有效的示例:
您可以将工作表中的数据范围推入一行而不用循环的数组中
DataArr = wsMain.Range("A2:D" & LastRow).Value
您只需要2个循环即可进行替换:
您的模板str
尚未在循环中初始化,但是您需要为每个数据行使用一个新的模板。
请注意,从范围加载的数组从1
开始计数,而变量数组从0
开始计数。
Option Explicit
Sub Example()
Dim Template As String
Template = "This is to confirm that strTitle has been enacted on strDate for strCompany."
'load your template string from worksheet here!
Dim Variables As Variant 'variables to be replaced
Variables = Array("strTitle", "strDate", "strCompany")
Dim wsMain As Worksheet
Set wsMain = ThisWorkbook.Worksheets("Main")
Dim LastRow As Long 'this method is more reliable to find the last used row
LastRow = wsMain.Cells(wsMain.Rows.Count, "A").End(xlUp).Row
Dim DataArr As Variant 'load the complete data range into an array
DataArr = wsMain.Range("A2:D" & LastRow).Value
Dim Output As String
Dim iRow As Long, iVar As Long
For iRow = LBound(DataArr, 1) To UBound(DataArr, 1) '1 to LastRow
Output = Template 'initialize with the template!
For iVar = LBound(Variables) To UBound(Variables) ' 0 to 2
Output = Replace(Output, Variables(iVar), DataArr(iRow, iVar + 1))
Next iVar
Debug.Print Output
Next iRow
End Sub