我编写了此脚本,该脚本遍历一列,并且如果在其中找到一个值并在另一列中找到一个值,则更改另一列的值。
Sub RepChange()
Const Company As String = "Kellog's"
Const Representer As String = "Elite"
Const NewRepresenter As String = "Core"
Const cSheet As Variant = "Sheet1"
Const cColRep As Variant = "H"
Const cColComp As Variant = "I"
Const cFR As Long = 2
Dim LR As Long
Dim i As Long
With ThisWorkbook.Worksheets(cSheet)
LR = .Columns(cColComp).Cells(.Rows.Count).End(xlUp).Row
For i = cFR To LR
If StrComp(.Cells(i, cColComp), Company, vbTextCompare) = 0 And _
StrComp(.Cells(i, cColRep), Representer, vbTextCompare) _
= 0 Then .Cells(i, cColRep) = NewRepresenter
Next
End With
MsgBox "Operation finished successfully.", vbInformation, "Success"
End Sub
工作正常。现在,我想使用前三个常量作为Sub的参数:
Sub RepChange2(Company As String, Representer As String, _
NewRepresenter As String)
Const cSheet As Variant = "Sheet1"
Const cColRep As Variant = "H"
Const cColComp As Variant = "I"
Const cFR As Long = 2
Dim LR As Long
Dim i As Long
With ThisWorkbook.Worksheets(cSheet)
LR = .Columns(cColComp).Cells(.Rows.Count).End(xlUp).Row
For i = cFR To LR
If StrComp(.Cells(i, cColComp), Company, vbTextCompare) = 0 And _
StrComp(.Cells(i, cColRep), Representer, vbTextCompare) _
= 0 Then .Cells(i, cColRep) = NewRepresenter
Next
End With
End Sub
所以我可以使用以下内容:
Sub Kellogs()
RepChange2 "Kellog's", "Elite", "Core"
End Sub
但是会产生以下错误:
编译错误:需要常量表达式
在线
With ThisWorkbook.Worksheets(cSheet)
其中cSheet
呈灰色。如果我将其替换为“ Sheet1”,则下一行会发生另一个错误:
LR = .Columns(cColComp).Cells(.Rows.Count).End(xlUp).Row
其中cColComp
呈灰色等。将Variants
更改为Strings
无济于事。
不胜感激。
答案 0 :(得分:1)
我无法重现此错误。错误说明与您提供的代码不匹配;你显然有常数。
也许创建一个新的工作簿并将此代码复制到其中,这是我唯一能想到的。
答案 1 :(得分:0)
我遇到了同样的问题:我在函数的开头定义了常量,并在所述函数中使用了这些常量。我收到了与OP相同的错误消息。
要解决此问题,我只需从模块中剪切功能并将其粘贴到另一个模块中即可。我立即能够按预期运行该函数,而没有任何“持续要求”错误。最后,我将函数移回了原始模块(剪切和粘贴)。仍然有效。
幸运的是,我不必创建新的工作簿。我的工作簿中充斥着工作表设计,各种命名的单元格等等,如果在新工作簿中从头开始复制所有内容,那将是一场噩梦。