未设置对象变量或With块变量-查找和替换宏-多个查找迭代

时间:2019-06-10 17:27:18

标签: excel vba replace

运行宏时,出现错误“对象变量或未设置块变量”。我不确定哪个变量设置不正确,现在如何确定它。

我已尝试并确保所有变量均已正确设置,但我很确定自己缺少某些内容。

Sub NewMonth_Setup()

'
'Find and Replace
'
Dim sht As Worksheet
Dim fnd1 As Variant
Dim rplc1 As Variant
Dim fnd2 As Variant
Dim rplc2 As Variant
Dim fndList As Variant
Dim rplcList As Variant
'Activates currently selected sheet
    Sheets(ActiveSheet.Name).Select
'
'Replaces old table name with new
    fnd1 = InputBox("Old Table Name: _MMYYWS")
    rplc1 = InputBox("New Table: _MMYYWS")
    fnd2 = InputBox("Old Table Name: _MMYY")
    rplc2 = InputBox("New Table: _MMYY")
'
    fndList = Array(fnd1, fnd2)
    rplcList = Array(rplc1, rplc2)
'
' Perform Find/Replace All
    sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
        LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
        SearchFormat:=False, ReplaceFormat:=False
'
MsgBox "I have completed my search and made replacements"
'


End Sub

预期结果将采用用户输入的两个变量,并分别替换它们。它正在替换输入,但仍然返回错误并且不输出MsgBox

1 个答案:

答案 0 :(得分:2)

您无法针对Nothing进行成员通话。您已经在此处声明了对象变量:

Dim sht As Worksheet

这会在内存中保留一个可以存储对象引用的位置,并且在该引用为Set之前,VBA会将此存储空间理解为Nothing-在其他语言中,它可能是{{1 }}或类似的概念:最重要的是,该地址没有有效的对象引用,因此当您尝试访问它时,VBA会引发错误91 ...

null

这不需要做:

sht.Cells.Replace ...

相反,Sheets(ActiveSheet.Name).Select Set对象引用:

sht

这应该可以解决...假设Set sht = ActiveSheet ' or, get a worksheet reference from the Workbook.Worksheets collection 被赋予 somewhere 值。大概搜索是要循环运行的?为此,您需要一个循环构造:

x