获取编译错误:检测到错误的名称:Worksheet_Selection更改

时间:2012-08-31 12:54:19

标签: excel excel-vba vba

附件是我在工作表中使用的代码。这段代码到最后一点工作。最后一个代码的第一行是错误的地方...... Private Sub Worksheet_SelectionChange(ByVal Target As Range)我想知道为什么,它似乎适用于其他两个主题。

如果有人能提供帮助,我们将不胜感激。

Option Explicit

Dim PreviousValue

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim sLogFileName As String, nFileNum As Long, sLogMessage As String
    Dim NewVal

    On Error GoTo Whoa

    Application.EnableEvents = False

    sLogFileName = ThisWorkbook.path & Application.PathSeparator & "Open Order Log.txt"

    If Not Target.Cells.Count > 1 Then
        If Target.Value <> PreviousValue Then
            If Len(Trim(Target.Value)) = 0 Then _
            NewVal = "Blank" Else NewVal = Target.Value

            sLogMessage = Now & Application.UserName & _
            " changed cell " & Target.Address & " from " & _
            PreviousValue & " to " & NewVal

            nFileNum = FreeFile
            Open sLogFileName For Append As #nFileNum
            Print #nFileNum, sLogMessage
            Close #nFileNum
        End If

    End If
LetsContinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    PreviousValue = Target(1).Value
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim sLogFileName As String
End Sub
    If FileLen(sLogFileName) > 3145728# Then
        sLogFileName = "Open Order Log - " & Format(Date, "dd-mm-yyyy")
        Name sLogFileName As "ThisWorkbook.path & Application.PathSeparator & \Temp\Open Order Log - " & Format(Date, "dd-mm-yyyy")
    End If
End Sub

3 个答案:

答案 0 :(得分:2)

您已在End Sub之后关闭Dim sLogFileName As String,这是错误的。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim sLogFileName As String
    If FileLen(sLogFileName) > 3145728# Then
        sLogFileName = "Open Order Log - " & Format(Date, "dd-mm-yyyy")
        Name sLogFileName As "ThisWorkbook.path & Application.PathSeparator & \Temp\Open Order Log - " & Format(Date, "dd-mm-yyyy")
    End If
End Sub

答案 1 :(得分:0)

解决了这个问题,End Sub被之前的帖子删除了Private Sub Size_Adjust(ByVal Target As Range) Dim sLogFileName As String If FileLen(sLogFileName) > 3145728# Then sLogFileName = "Open Order Log - " & Format(Date, "dd-mm-yyyy") Name sLogFileName As "ThisWorkbook.path & Application.PathSeparator & \Temp\Open Order Log - " & Format(Date, "dd-mm-yyyy") End If End Sub 之后的两个Subs ...

{{1}}

答案 2 :(得分:0)

您定义了以下代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    PreviousValue = Target(1).Value
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim sLogFileName As String
    'other stuff
End Sub

您有两个不同的 ,称为Worksheet_SelectionChange。您需要确定要使用的内容并重命名/删除另一个。