VBA“编译错误:语句在类型块之外无效”

2024-01-01

我正在 Excel 2010 中运行 VBA 宏并进行大量计算,因此数据类型非常重要,以尽可能缩短宏执行时间。

我的优化想法是让用户选择所有数字将被声明为什么数据类型(同时指出每种数据类型的优缺点,准确性/灵活性和CPU密集度/宏执行时间之间的平衡)。但是,当我运行宏时,我收到以下错误消息:

编译错误:

语句在 Type 块之外无效

这是代码中有问题的部分:

Ind2 As Double, BgrValP As Double, BgrRow As Double, M40eff As Double

这是宏的相关部分:

' Develop fake data to at glance recognize whether program works.
' Source http://www.cpearson.com/excel/optimize.htm
Option Explicit

Private Sub Function1()
On Error GoTo ErrorHandler
Dim userChoice As Variant
Dim strPath As String, strFileN As String, strDirN As String, strRangeNOut As String, strRangeNIn As String, strFilename As String, strTLCorn As String, strBRCorn As String, strSelectedFile As String, strtemp_name As String
Dim lngCount As Long
Dim vResMatrix(), vCPath, vFileN As Variant

'   MEeff = measure of efflux due to crudely purified HDL in scintillation
'   https://msdn.microsoft.com/en-us/library/ae55hdtk.aspx

'   Give the user macro options based on how fast or slow the computer is
userChoice = MsgBox("This macro by default treats all numbers as doubles for maximum precision. If you are running this macro on an old computer, you may want to redeclare numbers as singles, to speed up the macro." & vbNewLine & "You can also use integers for a quick estimate of data results.")

If userChoice = "Double" Then
    Dim RangeNOut As Double, vRangeNIn As Double, Ind6 As Double, Ind4 As Double, Ind5 As Double
    Dim Step2 As Double, MRow As Double, ColIn As Double, Ind3 As Double, Mcol As Double
    Dim MxRNo As Double, BgrSum As Double, RowIn As Double, Ind As Double, M40eff As Double, Step As Double
    Dim ColNo As Double, Startcol As Double, Startrow As Double, MeanComp As Double
    Dim PlateNo As Double, MonoVal As Double, Ind1 As Double, EntryRow2 As Double, EntryRow As Double
    Ind2 As Double, BgrValP As Double, BgrRow As Double, M40eff As Double
    Dim BrgSum As Double, BgrVal As Double, RangeNIn As Double, RangeNOut As Double, TLCorn As Double
    Dim Volcorr As Double, BRCorn As Double, MEeff As Double, MediaVal As Double

ElseIf userChoice = "Integer" Then
    Dim RangeNOut As Integer, vRangeNIn As Integer, ecInd6 As Integer, Ind4 As Integer, Ind5 As Integer
    Dim Step2 As Integer, MRow As Integer, ColIn As Integer, Ind3 As Integer, Mcol As Integer
    Dim MxRNo As Integer, BgrSum As Integer, RowIn As Integer, Ind As Integer, M40eff As Integer
    Dim Step As Integer, ColNo As Integer, Startcol As Integer, Startrow As Integer, MeanComp As Integer
    Dim PlateNo As Integer, MonoVal As Integer, Ind1 As Integer, EntryRow2 As Integer, EntryRow As Integer
    Dim Ind2 As Integer, BgrValP As Integer, BgrRow As Integer, M40eff As Integer
    Dim BrgSum As Integer, BgrVal As Integer, RangeNIn As Integer, RangeNOut As Integer, TLCorn As Integer
    Dim Volcorr As Integer, BRCorn As Integer, MEeff As Integer, MediaVal As Integer

ElseIf userChoice = "Single" Then
    Dim RangeNOut As Single, vRangeNIn As Single, ecInd6 As Single, Ind4 As Single, Ind5 As Single
    Step2 As Single, MRow As Single, ColIn As Single, Ind3 As Single, Mcol As Single
    Dim MxRNo As Single, BgrSum As Single, RowIn As Single, Ind As Single, M40eff As Single, Step As Single
    Dim ColNo As Single, Startcol As Single, Startrow As Single, MeanComp As Single
    Dim PlateNo As Single, MonoVal As Single, Ind1 As Single, EntryRow2 As Single, EntryRow As Single
    Ind2 As Single, BgrValP As Single, BgrRow As Single, M40eff As Single
    Dim BrgSum As Single, BgrVal As Single, RangeNIn As Single, RangeNOut As Single, TLCorn As Single
    Volcorr As Single, BRCorn As Single, MEeff As Single, MediaVal As Single

Else
    GoTo Function1
    MsgBox("This is not a supported data type: double, single, or integer.", vbCritical, "Unsupported Data Type")

这是我目前使用的代码:

Private Sub Function2(ByVal VarType As String)

Dim mVers As String
Dim userChoice As Variant

'   Give the user macro options based on how fast or slow the computer is using advanced conditional compliling
userChoice = MsgBox("This macro by default treats all numbers as doubles for maximum precision. If you are running this macro on an old computer, you may want to relare numbers as singles, to speed up the macro." & vbNewLine & "You can also use integers for a quick estimate of data results.")
userChoice = VarType

#If VarType = "Double" Or "double" Then
    Dim RangeNOut As Double, vRangeNIn As Double, Ind6 As Double, Ind4 As Double, Ind5 As Double
    Dim Step2 As Double, MRow As Double, ColIn As Double, Ind3 As Double, Mcol As Double
    Dim MxRNo As Double, BgrSum As Double, RowIn As Double, Ind As Double, M40eff As Double, Step As Double
    Dim ColNo As Double, Startcol As Double, Startrow As Double, MeanComp As Double
    Dim PlateNo As Double, MonoVal As Double, Ind1 As Double, EntryRow2 As Double, EntryRow As Double
    Dim Ind2 As Double, BgrValP As Double, BgrRow As Double, M40eff As Double
    Dim BrgSum As Double, BgrVal As Double, RangeNIn As Double, RangeNOut As Double, TLCorn As Double
    Dim Volcorr As Double, BRCorn As Double, MEeff As Double, MediaVal As Double
#ElseIf VarType = "Single" Or "single" Then
    Dim RangeNOut As Single, vRangeNIn As Single, ecInd6 As Single, Ind4 As Single, Ind5 As Single
    Step2 As Single, MRow As Single, ColIn As Single, Ind3 As Single, Mcol As Single
    Dim MxRNo As Single, BgrSum As Single, RowIn As Single, Ind As Single, M40eff As Single, Step As Single
    Dim ColNo As Single, Startcol As Single, Startrow As Single, MeanComp As Single
    Dim PlateNo As Single, MonoVal As Single, Ind1 As Single, EntryRow2 As Single, EntryRow As Single
    Dim Ind2 As Single, BgrValP As Single, BgrRow As Single, M40eff As Single
    Dim BrgSum As Single, BgrVal As Single, RangeNIn As Single, RangeNOut As Single, TLCorn As Single
    Dim Volcorr As Single, BRCorn As Single, MEeff As Single, MediaVal As Single
#ElseIf VarType = "Integer" Or "integer" Then
    Dim RangeNOut As Integer, vRangeNIn As Integer, ecInd6 As Integer, Ind4 As Integer, Ind5 As Integer
    Dim Step2 As Integer, MRow As Integer, ColIn As Integer, Ind3 As Integer, Mcol As Integer
    Dim MxRNo As Integer, BgrSum As Integer, RowIn As Integer, Ind As Integer, M40eff As Integer
    Dim Step As Integer, ColNo As Integer, Startcol As Integer, Startrow As Integer, MeanComp As Integer
    Dim PlateNo As Integer, MonoVal As Integer, Ind1 As Integer, EntryRow2 As Integer, EntryRow As Integer
    Dim Ind2 As Integer, BgrValP As Integer, BgrRow As Integer, M40eff As Integer
    Dim BrgSum As Integer, BgrVal As Integer, RangeNIn As Integer, RangeNOut As Integer, TLCorn As Integer
    Dim Volcorr As Integer, BRCorn As Integer, MEeff As Integer, MediaVal As Integer
#Else
    MsgBox "VarType " & VarType & " is not valid. Check spelling."
#End If

'   MEeff = measure of efflux due to crudely purified HDL in scintillation
MsgBox "For additional information about this macro:" & vbNewLine & "1. Go to tab Developer" & vbNewLine & "2. Select Visual Basic or Macro." & vbNewLine & "See the comments or MsgBoxes (message boxes)."

'   Start File Explorer to select file containing data (simple GUI, much easier than coding in the file)

With Application.FileDialog(msoFileDialogOpen)
    .AllowMultiSelect = True
    .Show

'   Display paths of each file selected
    For lngCount = 1 To .SelectedItems.Count
    Next lngCount
    For Each strFilename In .SelectedItems
        MsgBox strFilename
        Function2
    Next
End With

ErrorHandler:
MsgBox "Error detected" & vbNewLine & "Error" & Err.Number & ": " & Err.Description, vbCritical, "Error Handler: Error " & Err.Number
MsgBox "If you want to force the program to run, go to the line below and insert a ' mark to comment the line out." & vbNewLine & "On Error GoTo ErrorHandler", vbCritical, "Error Handler: Error " & Err.Number

End Sub

你有:

Dim RangeNOut as Double
Dim RangeNOut as Integer

虽然IF语句中有一个好主意,VBA 不会允许你这样做。它不进行条件“编译”,因为它不是编译语言。当 VBA 运行您的代码时,所有变量都会被声明(无论代码中的哪个位置)Dim语句位于),然后代码开始执行。

您想出的主意不错,但在 VBA 中尝试这一点就像在枪战中带一块 Silly Putty™ 一样 - 它根本无法完成这项工作。

另外,如果你是that如果您关心执行速度,VBA 也不是您选择的武器。我没有任何统计数据来支持它,但我怀疑您实际上会看到基于三种不同变量类型的执行速度有很大差异。

要将变量类型作为参数传递给函数,请使用以下命令:

Private Sub Function1(ByVal VarType as String)

  #If VarType = "Double" then
    ...
  #ELSEIF VarType = "Single" then
    ...
  #ELSEIF VarType = "Integer" then
    ...
  #ELSE
    MsgBox "You passed in a 'VarType' of " & VarType & " - that's not valid"
  #ENDIF

另外,我刚刚注意到在你的期末考试中Else你有Goto Function1。我不确定你想在那里完成什么,但是:

  1. 不要使用goto。除了 VBA 风格的错误处理之外,它是几乎从不必要的
  2. 您没有为以下定义的标签Goto无论如何,要跳到。

也可以看看VBA函数重载 https://hammondmason.wordpress.com/2015/06/23/object-oriented-vba-overloading/另一种可能的选择。

Notice:尽管有赞成票和已接受的答案状态,我还是尝试了以下操作,结果DOES NOT按照OP的要求工作:

Sub test()
  func "Double"
  func "Single"
  func "Integer"
  func "String"
End Sub

Function func(v As String)
  #If v = "Double" Then
    Dim myvar As Double
    Range("A1") = "MyVar type is: " & vartype(v)
  #ElseIf v = "Single" Then
    Dim myvar As Single
    Range("a2") = "MyVar type is: " & vartype(v)
  #ElseIf v = "Integer" Then
    Dim myvar As Integer
    Range("a3") = "MyVar type is: " & vartype(v)
  #Else
    Range("A4") = "Invalid var type passed: " & v
  #End If

  MsgBox "Passed in " & v

End Function

所有来电Func()最终在#Else代码段,填充Range("A4")Invalid var type passed: text.

遗憾的是,这行不通。

如果确实有必要让具有不同变量类型的函数执行完全相同的操作,我认为以下内容将是最好的选择:

Sub Test()
  Dim VType as String

  While Vtype <> "Integer" and VType <> "Double" and VType <> "Single" and VType <> "Cancel"
    vType = msgBox("Enter variable type")
  Wend

  If VType = "Integer" then
    MyFuncInt()
  ElseIf VType = "Double" then
    MyFuncDouble()
  Elseif VType = "Single"
    MyFuncSingle()
  Else
    MsgBox "Function call cancelled"
  End if
End Sub

Function MyFuncInt()
  Dim AllTheVars as Integer
  ...
End Function

Function MyFuncDouble()
  Dim AllTheVars as Double
  ...
End Function

Function MyFuncSingle()
  Dim AllTheVars as Single
  ...
End Function
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VBA“编译错误:语句在类型块之外无效” 的相关文章

随机推荐

  • Google 容器注册表权限

    我正在尝试将 docker 映像推送到 GCP 但仍然收到此错误 unauthorized You don t have the needed permissions to perform this operation and you ma
  • 访问 DataReader 中的特定行

    我有一个数据读取器 可以在 js 轮播中显示比赛周列表 我需要能够添加一个 if 语句来更改当前游戏周的 div 类 这是我当前的代码 if dReader HasRows while dReader Read gameweekList T
  • 当 cfhttp 上 throwonerror=true 时如何获取 cfhttp.filecontent ?

    我使用以下命令进行 REST 服务调用cfhttp与throwonerror属性设置为 true 当我使用 try catch 语句捕获错误时 我似乎找不到一种方法来输出 REST 服务调用尝试返回的错误 该错误将驻留在cfhttp fil
  • 如何从 C# 应用程序调用 docker run

    我有一个 WPF 应用程序 在处理文件时需要使用 docker 进程 docker 容器构建在盒子上 目前在使用 WPF 应用程序处理文件后 用户必须启动命令提示符并输入 docker run it rm v folderdedirect
  • 尝试一下,catch似乎不起作用

    我有以下代码 我认为它可以让我捕获错误 而不是生成错误 写出 发生错误 不幸的是 它仍然显示错误 无法重新启动计算机 访问被拒绝 我知道为什么会发生这种情况 但我希望能够捕获错误并重新格式化它 我究竟做错了什么 try Restart Co
  • 使用 Hibernate 和 JPA 映射 Map

    我尝试以下映射 ElementCollection private Map
  • 使用 iTextSharp 从现有 PDF 中读取 XMP

    如何使用 iTextSharp 从现有 PDF 文件中读取 XMP 我对 itextSharp 非常无知 但这对我来说很有效 PdfReader pdf new PdfReader fileName string metadataXml S
  • HTML + Javascript 渲染器输出 HTML 或纯文本?

    如果我使用 String plain Html fromHtml html toString 渲染简单的 html 其中包含 any plain vanila HTML goes here 一切都美好而花花公子 但是 如果该页面包含大量 J
  • Java 如何使 JFrame 作为最大化窗口启动

    我想知道如何使 java JFrame 最大化 我不希望它是全屏的 周围没有窗口 我只是希望它像普通程序 例如网络浏览器 一样启动 我已经知道如何使用 Dimension screenSize Toolkit getDefaultToolk
  • Safari - 当选项卡位于后台时,HTML5 音频不会播放

    我有一个反应应用程序 它使用反应声音 基本上是 HTML5 音频 在触发新通知时播放声音 我希望当选项卡在 Safari 中处于后台时播放此声音 但这似乎不起作用 当选项卡位于前台时 声音会播放 有谁知道这个问题的解决方法 None
  • Chrome 中的 .blur 和 .onblur

    更新了没用 http jsfiddle net xvepL 4 http jsfiddle net xvepL 4 让我有点抓狂 Chrome 不使用 blur 仅适用于 onblur 但其他浏览器使用 blur 有没有办法解决这个问题 这
  • 自动热键 3 次点击 = 音量静音

    在 autohotkey 中 我试图做到这一点 以便当我按下鼠标左键 3 次并延迟 10 毫秒它变成音量静音 LButton if Send Volume Mute else Send LButton Return Use A TickCo
  • Pytest 仅运行具有特定标记属性的测试

    我在用着 pytest mark为了唯一地标识特定的测试 因此我创建了自定义标记 pytest mark key 我这样使用它 pytest mark key test 001 def test simple self self passi
  • 在 PHP 中使用heredoc有什么好处? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • Jquery 如果单选按钮被选中

    可能的重复 检查特定单选按钮是否已选中 https stackoverflow com questions 2195125 check of specific radio button is checked 我目前有这 2 个单选按钮 以便
  • nginx 和带有代理传递的尾部斜杠

    我对 nginx 1 4 1 使用以下配置 server listen 8000 server name correct name gr location test register proxy set header X Forwarded
  • WPF 按钮图标被镜像,为什么?

    当按如下方式定义图像时 此按钮看起来不错 请参见屏幕截图 请注意 带有字母 T 的盾形图标已正确显示
  • getnameinfo() - 反向 DNS 查找(IP 地址到主机名)C/C++

    对于 IPAddress 66 249 68 9 dig x 正确地说 crawl 66 249 68 9 googlebot com 我可爱的程序声称它是 ip68 9 0 0 ri ri cox net 我不在乎我最终是否会采用类似于下
  • 获取内存制造商

    有谁知道如何以编程方式检索 RAM 内存制造商 Thanks 现代 RAM 芯片上有一个附加的 EPROM 其中包含有关 RAM 的大量信息 其标准是 SPD 即串行存在检测 至少某些版本的 SPD 包含 JDEC 制造商代码 Look a
  • VBA“编译错误:语句在类型块之外无效”

    我正在 Excel 2010 中运行 VBA 宏并进行大量计算 因此数据类型非常重要 以尽可能缩短宏执行时间 我的优化想法是让用户选择所有数字将被声明为什么数据类型 同时指出每种数据类型的优缺点 准确性 灵活性和CPU密集度 宏执行时间之间