我有excel问题。我插入了一张图片作为参考。
我需要替换D1单元格中的文本,其中文本与A列中的任何id匹配,我需要将其替换为B列中包含的每个id的对应文本。
我有一个代码来替换D1单元格中的id,但问题是某些文本超过了255个字符并且它给了我一个"类型不匹配(错误13)&# 34;错误。代码看起来像这样:
Sub ReplaceText()
For i = 2 To LastRow
id = Range("A" & i).Value
textToReplace = Range("B" & i).Value
Worksheets("Sheet1").Columns("D:Z").Replace What:=id, Replacement:=textToReplace, LookAt:= _
xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next i
End Sub
我想知道我能做些什么来插入超过255个字符的文字。
非常感谢!
答案 0 :(得分:0)
要解决此问题,请将<<< 256个字符,像这样
Option Explicit ' first line in Module
Sub ReplaceText()
Dim lastRow As Long, i As Long
Dim ID As String, TextToReplace As String, Text As String
Dim Mark As String, MaxLen As Long
Dim SearchRange As Range
MaxLen = 200
' Choose a character for Mark that is not in your data,
' and is not a special char: ~?*
Mark = "@"
lastRow = 6 ' set this to suit
Set SearchRange = Worksheets("Sheet3").Columns("D:Z")
For i = 2 To lastRow
ID = Range("A" & i).Value
TextToReplace = Range("B" & i).Value
If ID <> vbNullString Then
Do
Text = Left$(TextToReplace, MaxLen) & Mark
' Terminate the loop when all of TextToReplace has been processed
If Text = Mark Then Text = vbNullString
TextToReplace = Mid$(TextToReplace, MaxLen + 1)
SearchRange.Replace _
What:=ID, _
Replacement:=Text, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
ID = Mark
Loop Until Text = vbNullString
End If
Next i
End Sub