Excel VBA字符串操作导致运行时错误“1004”

问题描述:

因此,我在RenPy上制作了一个视觉小说,并且我不得不在整个文档上换掉句子。Excel VBA字符串操作导致运行时错误“1004”

由于修订版本出现在excel文件中,我决定使用excel宏自动修复。 有三列。原始行,建议的修复程序和原始脚本。

example

所以我撞了一个脚本,它是这样的:

Sub MacroVOID() 
Dim x As Integer 
Dim y As Long 
x = 2 
y = 2 

Do While x < 298 
If StrComp(Cells(x, 1).Value, Cells(y, 3).Value, vBinaryCompare) = 0 Then 
    Cells(y, 3).Value = Cells(x, 2).Value 
    x = x + 1 
    Else 
    y = y + 1 
End If 
Loop 

End Sub 

这就造成了运行时错误 “1004”。

我在工作表级别保存了宏。

我是这个东西的新手,所以任何帮助,将不胜感激。

+1

您的宏由于缺少定义的工作表而无法在activesheet上运行。这可能会导致你的错误。你也检查两个字符串是否相等,如果有的话替换。我想你会更好地阅读Strcomp的语法:https://www.techonthenet.com/excel/formulas/strcomp.php – Luuklag

+4

它是vbBinaryCompare,而不是vBinaryCompare。我建议你在你的工作表顶部使用'Option Explicit'。这会提醒你像这样的错别字。添加@Luuklag写的内容,StrComp比较字符串。您比较的两个值是变体,不一定是字符串。您可以通过使用Cstr(Cells(x,1).value)将它们转换为两个值进行比较。 – Variatus

试试这个


Option Explicit 

Public Sub ReplaceStrings() 
    Dim ws As Worksheet, cel As Range 

    Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- Update Sheet Name 

    With ws.UsedRange 
     For Each cel In .Columns(1).Cells  'iterate through all used cells in col A 
      If Len(cel.Value2) > 0 Then   'if the cell is not empy 

       'in column 3: replace all instances of values in current cell 
       'with the value in (current cell).offset by one column to its right (col B) 
       .Columns(3).Replace cel.Value2, cel.Offset(0, 1).Value2, xlWhole 

      End If 
     Next 
    End With 
End Sub 

的Range.Replace方法有以下参数:

Replace(What, Replacement, LookAt, SearchOrder, MatchCase, MatchByte, SearchFormat, ReplaceFormat)"

更多细节从帮助:

  • 什么:必需的变体您希望Microsoft Excel搜索的字符串。
  • 替换:必需的变体替换字符串。
  • LookAt:可选变体可以是以下XlLookAt常量之一:xlWhole或xlPart。
  • SearchOrder:可选Variant可以是以下XlSearchOrder常量之一:xlByRows或xlByColumns。
  • MatchCase:可选变体正确使搜索区分大小写。
  • MatchByte:可选Variant只有在Microsoft Excel中选择或安装了双字节语言支持时,才可以使用此参数。如果双字节字符只匹配双字节字符,则为真。假使双字节字符与它们的单字节等价物匹配。
  • 搜索格式:可选Variant该方法的搜索格式。
  • ReplaceFormat:可选Variant该方法的替换格式。
+0

你的代码有效,但有些没有被替换?你能通过你的代码走过我吗?我想试着去理解它。谢谢你的帮助:) –

+0

没关系我找到了。这是波浪号。原来有歪斜,修复有一个直线代字符。感谢您的帮助 –

+0

我添加了更多关于每个步骤的详细信息@RizkyGustiantoWibisono –