Excel VBA应该可以工作,但事实并非如此

时间:2014-07-04 16:41:50

标签: excel vba excel-vba search

我想要做的是,当我保存我的excel文件时,我希望脚本检查所有具有" $"的单元格。作为最后一个字符并检查是否有一个名为&#34的单元格;备份"在与发现一个单元格相同的列中,如果有,则只应用我的脚本

这是我的代码:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim c As Range
Dim x As Integer
Dim y As Integer
Dim isbackup As Boolean
isbackup = False

For Each c In Range("A1:N60")
If Right(c, 1) = "$" Then y = c.Column: x = c.Row
    For i = 1 To 60
        If Cells(i, y).Value = "Backup" Then
            isbackup = True
            Exit For
        End If
    Next i
If isbackup = True And Right(c, 1) = "$" Then <my script>
Next c

我没有看到任何语法或逻辑错误,但我收到了错误代码

  

1004:&#34;应用程序定义或对象定义的错误&#34;

1 个答案:

答案 0 :(得分:1)

也许这可能会有所帮助:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim c As Range
    Dim x As Integer, y As Integer
    Dim isbackup As Boolean
    isbackup = False

    Dim rng As Range
    Set rng = ThisWorkbook.Worksheets(1).Range("A1:N60")

    For Each c In rng

        If Right(c, 1) = "$" Then
            y = c.Column: x = c.Row

            Dim i As Integer
            For i = 1 To rng.Rows.Count '--> I find this more flexible
                If Cells(i, y).Value = "Backup" Then
                    isbackup = True
                    Exit For
                End If
            Next i

        End If

        If isbackup = True And Right(c, 1) = "$" Then DoEvents 'Replaced by your script

    Next c
End Sub