Excel 查找并替换
我写了一个宏,它工作得很好,但看起来好像有某种更新,现在我的代码不工作了。有谁能帮我找出哪里出了问题,或者为什么这个函数不再工作了 以下是实际的功能:Excel 查找并替换,excel,vba,excel-formula,excel-2010,Excel,Vba,Excel Formula,Excel 2010,我写了一个宏,它工作得很好,但看起来好像有某种更新,现在我的代码不工作了。有谁能帮我找出哪里出了问题,或者为什么这个函数不再工作了 以下是实际的功能: Function FindReplace(CellValue$) Dim strPattern$: strPattern = "[^A-Za-z, ]+" 'Pattern to only take care of letters Dim strReplace$: strReplace = "" 'Replace ev
Function FindReplace(CellValue$)
Dim strPattern$: strPattern = "[^A-Za-z, ]+" 'Pattern to only take care of letters
Dim strReplace$: strReplace = "" 'Replace everything else with blank
Dim regex As Object
Set regex = CreateObject("vbscript.regexp")
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
FindReplace = regex.Replace(CellValue, strReplace) 'RegEx Function replaces the pattern with blank
End Function
我试着让它看一个单元格,只允许特定的字符出现
以下是此函数所属的较大代码:
'Concatenate all the data in the rows into columns A
Sheets("Formula2").Select
Dim Lastrow%: Lastrow = ActiveSheet.UsedRange.Rows.Count
Dim strConcatenate$, I%, j%
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = ActiveSheet
Range("A:A").Clear
For I = 1 To Lastrow
For j = 2 To lastColumn(I) 'Calls function "LastColumn" to get the last column of each row
strConcatenate = strConcatenate & FindReplace(ws.Cells(I, j))
Next j
ws.Cells(I, 1) = strConcatenate 'This will past the finished string into column [A] in the specific row
strConcatenate = "" 'blanks the string, so the next string in the next row is fresh
Next I
我建议使用A、B、C 123测试以下代码 请注意,您需要调整For j=2到3循环,以在最后一列结束
Option Explicit
Sub Test()
'Concatenate all the data in the rows into columns A
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Formula2") 'avoid select and specify the sheet by name
Dim LastRow As Long
LastRow = ws.UsedRange.Rows.Count
Dim strConcatenate As String
Dim i As Long, j As Long
ws.Range("A:A").Clear 'always specify in which sheet a range is!
For i = 1 To LastRow
For j = 2 To 3 'changed that for testing to 3
strConcatenate = strConcatenate & FindReplace(ws.Cells(i, j).Value)
Next j
ws.Cells(i, 1).Value = strConcatenate
strConcatenate = ""
Next i
End Sub
Function FindReplace(CellValue As String) As String
Dim strPattern As String
strPattern = "[^A-Za-z, ]+" 'Pattern to only take care of letters
Dim strReplace As String
strReplace = "" 'Replace everything else with blank
Dim regex As Object
Set regex = CreateObject("vbscript.regexp")
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
FindReplace = regex.Replace(CellValue, strReplace) 'RegEx Function replaces the pattern with blank
End Function
代码不工作没有有用的错误描述。请告诉我你在哪里遇到了什么错误,或者你的代码做了什么,或者你期望你的代码实际应该做什么。另外,请提供一个有效的输入/输出示例数据,说明您的期望和代码的功能。如果我有一个带有值测试的单元格,当我使用此公式时,值将变为值!不要停留在测试的状态。从一个子系统而不是从工作表中调用你的函数-然后你就可以调试了。我用a,B测试,C 123测试了你的代码,它完全按照你说的做了。它将测试写入A1,我只是将lastColumnI替换为3进行测试。避免使用。Select和ActiveSheet请改为按名称引用工作表。因此,将lastColumnI更改为使用长数据类型,然后注意,调用不会出现在发布的代码中的任何位置。在处理行时,不应该在任何地方使用整数。