0

Excel VBA と次の方法を使用して、html ファイル内の文字列を検索し、太字タグを追加して同じ文字列に置き換えます。

FindAndReplace ("C:\xxx.htm", "hello world", "<b>hello world</b>")

Private Sub FindAndReplace(filePath As String, findWhat As String, replaceWith As String)

Dim nextFileNum As Long
Dim oldFileContents As String
Dim newFileContents As String
Dim textFileTypes() As String
Dim fileExtension As String

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim strFound As Integer

  If Len(Dir(filePath)) = 0 Then
    Exit Sub
  End If

  nextFileNum = FreeFile

  Open filePath For Input As #nextFileNum
  oldFileContents = Input$(LOF(nextFileNum), #nextFileNum)
  Close #nextFileNum

  newFileContents = Replace(oldFileContents, findWhat, replaceWith)

  nextFileNum = FreeFile

  Open filePath For Output As #nextFileNum
  Print #nextFileNum, newFileContents
  Close #nextFileNum
End Sub

私が直面している問題は、関数が文字列を見つけられないことです。html ソースコードの改行のために文字列が分割されている場合。

たとえば、コードが次の場合に文字列が検出されます。

<p>hi hola hello world</p>

ただし、コードが次の場合は見つかりません。

<p>hi hola hello 
world</p>

テキストの検索と置換に使用できる他の VBA メソッドはありますか、または上記のコードにいくつかの機能を追加して、その間の改行を無視することができます。

4

2 に答える 2

0

次のバリエーションを使用してみてください。

Function RemoveCarriageReturns(SourceString As String) As String

    Dim s As String

    'strip out CR and LF characters together
    s = Replace(SourceString, vbCrLf, "")

    'just in case, remove them one at a time
    s = Replace(s, Chr(13), "")
    s = Replace(s, Chr(10), "")

    RemoveCarriageReturns = s

End Function

ASCII 文字の 13 と 10 は、キャリッジ リターンとライン フィード文字です。

于 2012-11-21T13:23:38.110 に答える
0

分割が改行/リターン ( Chr(10), Chr(13)) および/またはスペースのみである場合は、Chr(32)最初に「hello」を検索するだけでかまいません。

見つかったら、それらの文字(10、13、および 32) を探し、他の何かに遭遇するまでそれらをスキップします (DO WHILE ... OR ... OR ... ORループを使用)。

次に、それ以外のものが「世界」であり、これらの文字の少なくとも 1 つが検出されたかどうかを確認します。

その場合、あなたはとに"hello"変わります"<b>hello""world""world</b>"

于 2012-11-21T14:11:30.260 に答える