VBA文字匹配

时间:2019-11-27 14:17:18

标签: excel vba match string-matching

我有一个包含两张纸的excel文件:母版纸和第二张纸。目前,Master有大约50行的一列,每行包含一个单词。第二页有23列,每列都有不同的长度,最大的列可达95行。我的目标是使用“母版”上的第一列在表2的每一列中搜索文本匹配项,然后将所有匹配项输出到表2上其相应列的下方。我遇到的问题是表2的第一列之后匹配非常参差不齐,经常会漏掉单词。任何改进我的代码的建议都将不胜感激(我是VBA的初学者)。

这是代码:

Sub CompareFNL()

Application.ScreenUpdating = False

Dim WS As Worksheet

Set WS = Sheets("Master")

Dim rng As Range

Dim Column2 As Integer

Dim RowsMaster As Integer, Rows2 As Integer

RowsMaster = WS.Cells(100, 1).End(xlUp).row

Rows2 = Worksheets(2).Cells(100, 1).End(xlUp).row

Column2 = Worksheets(2).Cells(1, 24).End(xlToRight).Column

' Get the number of used rows for each sheet


With Worksheets(2)

For c = 1 To Column2

For i = 1 To Rows2
    'Loop through Sheet 2

For j = 1 To RowsMaster

'Loop through the Master sheet

If .Cells(i, c) = WS.Cells(j, 1) Then

'If a match is found:

Worksheets(2).Cells(i + 110, c) = WS.Cells(j, 1)

'Copy int sheet2 in their respective columns

Exit For

End If

Next j

Next i

Next c


'Store blank cells inside a variable

On Error GoTo NoBlanksFound

Set rng = Range("a110:x250").SpecialCells(xlCellTypeBlanks)

On Error GoTo 0

'Delete blank cells and shift upward

rng.Rows.delete Shift:=xlShiftUp

'ERROR HANLDER

NoBlanksFound:

MsgBox "No Blank cells were found"

End With

Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

您是否可以添加.Cells(i,j).Value来查看其是否有效:

If .Cells(i, c).Value = WS.Cells(j, 1).Value Then