无法在Excel中定义对象

时间:2019-03-18 14:11:21

标签: excel vba

在下面的代码中,我将r声明为变量,并做了r = twb.Worksheets("Log").Range("b2"),但由于缺少对象而收到错误424。我认为通过声明并定义它可以解决问题。该代码在代码的“从单元格中选择值”部分中中断。

用于处理单元格中特殊字符的函数是:

Function ValidFileName(ByVal FileName As String) As String
Dim myarray() As Variant
Dim x
'check for illegal characters
myarray = Array("[", "]", "\\", "/", "*", "\", "?", "<>", "<", ">", ":", "|", "&")
For x = LBound(myarray) To UBound(myarray)
    FileName = Replace(FileName, myarray(x), "", 1)
Next x
ValidFileName = FileName
End Function

我要解析的代码是:

    Option Explicit

Sub RenameExcelInDir()

Dim MyPath As String
Dim MyFile As String
Dim MyExt As String
Dim MyNewName As String
Dim wb As Workbook
Dim twb As Workbook
Dim wks As Worksheet
Dim r As Variant '<---- Causing error
Dim getDate As Date


'Opens File Dialog Window to choose dir to search in

    With Application.FileDialog(msoFileDialogFolderPicker)
       .Show
       MyPath = .SelectedItems(1)
    End With

    Set twb = ThisWorkbook

    r = twb.Worksheets("Log").Range("B2")

    MyFile = Dir(MyPath & "\*.*")

    Do While Len(MyFile) > 0
        MyExt = Split(MyFile, ".")(UBound(Split(MyFile, ".")))

        Set wb = Workbooks.Open(MyPath & "\" & MyFile, UpdateLinks:=0)

'Loops through the worksheet collection

    For Each wks In wb.Worksheets

    Select Case wks.Name

        Case "ISU Form"
        MyNewName = ValidFileName(FileName:=wb.Sheets("ISU FORM").Range("C23").Value & "." & MyExt)

        Case "GLOBAL ISU"
        MyNewName = ValidFileName(FileName:=wb.Sheets("GLOBAL ISU").Range("M26").Value & "." & MyExt)

    End Select

    Next wks

    wb.Close

'Select Values from cells

    r.Value = MyFile
    r.Offset(, 1).Value = MyNewName
    Set r = r.Offset(1)
    Name MyPath & "\" & MyFile As MyPath & "\" & MyNewName
    MyFile = Dir

    Loop

End Sub

我不能将r用作变量吗?一定要别的吗?

0 个答案:

没有答案