简体   繁体   English

为什么我的 VBA 代码给了我“变量未定义”错误?

[英]Why is my VBA code giving me a “variable not defined” error?

I made a similar post a few days ago and got some good advice/help, but my code still seems to not be functioning properly.几天前我发表了一个类似的帖子并得到了一些很好的建议/帮助,但我的代码似乎仍然无法正常运行。 For reference, I am running 64 bit Excel and all of my code is contained within the same module.作为参考,我正在运行 64 位 Excel 并且我的所有代码都包含在同一个模块中。

I am trying to create a function that will read the value of a cell and play a specific WAV file associated with that value.我正在尝试创建一个 function 它将读取单元格的值并播放与该值关联的特定 WAV 文件。 For example, if the function reads "1", it will play "Amaj.wav", if it plays "2", it will play "Amin.wav", so on and so forth.例如,如果 function 读取“1”,则播放“Amaj.wav”,如果播放“2”,则播放“Amin.wav”,以此类推。 All of my WAV files are stored in the same directory as my workbook.我所有的 WAV 文件都存储在与我的工作簿相同的目录中。 Here is my current code (taken from the answers on my previous post):这是我当前的代码(取自我之前帖子的答案):

Option Explicit

Private Declare PtrSafe Function PlaySound Lib "winmm.dll" _
                Alias "PlaySoundA" (ByVal lpszName As String, _
                 ByVal hModule As Long, ByVal dwFlags As Long) As Long
Private ChordDict As New Collection
Sub ChordDictionary()
    Set ChordDict = Nothing
    ChordDict.Add "Amaj.wav", "1"
    ChordDict.Add "Amin.wav", "2"
    ChordDict.Add "Aaug.wav", "3"
    ChordDict.Add "Adim.wav", "4"
    ChordDict.Add "A#maj.wav", "5"
    ChordDict.Add "A#min.wav", "6"
    ChordDict.Add "A#aug.wav", "7"
    ChordDict.Add "A#dim.wav", "8"
    ChordDict.Add "Bmaj.wav", "9"

    Sound 3 'you call here the function, for the third collection element
End Sub
Function Sound(Cell As Long)
    Dim WAVFile As String, SoundFile As String
    Const SND_ASYNC = &H1
    Const SND_FILENAME = &H200000

    For i = 1 To ChordDict.Count
        If i = Cell Then
            SoundFile = ChordDict(i)

For some reason, whenever I try to run the "Sound()" function within my Excel workbook, I get a "compile error: variable not defined" message.出于某种原因,每当我尝试在 Excel 工作簿中运行“Sound()”function 时,都会收到“编译错误:变量未定义”消息。 The line that is highlighted is the "Function Sound(Cell As Long)."突出显示的行是“Function Sound(Cell As Long)”。 Does anyone have any advice for how I can get my code to function as intended?有人对我如何按预期将我的代码获取到 function 有任何建议吗? Thanks.谢谢。

Fixed function固定 function

Function Sound(Cell As Long)
    Dim WAVFile As String, SoundFile As String, i as long
    Const SND_ASYNC = &H1
    Const SND_FILENAME = &H200000

    For i = 1 To ChordDict.count
        If i = Cell Then
            SoundFile = ChordDict(i)
            WAVFile = ThisWorkbook.path & "\" & SoundFile
            Call PlaySound(WAVFile, 0&, SND_ASYNC Or SND_FILENAME)
            Exit Function
        End If
    Next
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM