【问题标题】:VBA Excel: Argument not optionalVBA Excel:参数不是可选的
【发布时间】:2016-08-04 16:17:47
【问题描述】:

对 vba 非常陌生,我在使用一段代码时遇到了一些问题。本质上,我正在尝试对用户表单中列表框中的用户选择的项目执行不同的工作表功能。

Private Sub cmdRunStat_Click()
Dim averageValue As Single
Dim sdValue As Single
Dim maxValue As Variant
Dim minValue As Single
Dim modeValue As Single
Dim UserRange As String, sheetName As String


Set UserRange = ListBox1.Selected = True


If optAverage.Value = True Then

  averageValue = WorksheetFunction.Average(UserRange)
  MsgBox "The average of the selected data is " & averageValue

ElseIf optSD.Value = True Then

   sdValue = WorksheetFunction.StDev(UserRange)
   MsgBox "The standard deviation of the selected data is " & sdValue

ElseIf optMax.Value = True Then

   maxValue = WorksheetFunction.Max(UserRange)
   MsgBox "The maximum of the slected data is " & maxValue

ElseIf optMin.Value = True Then

   minValue = WorksheetFunction.Min(UserRange)
   MsgBox "The minimum of the slected data is " & minValue

Else

    modeValue = WorksheetFunction.Mode(UserRange)
    MsgBox "The mode of the slected data is " & modeValue

End If

End Sub

【问题讨论】:

  • 你确定编译器错误不是Set UserRange = ListBox1.Selected = True行上的“需要对象”吗?
  • 您不能将 Set 值转换为字符串。这是错误的Set UserRange = ListBox1.Selected = True
  • 如果您使用 ListBox 输入表示范围的字符串,则需要使用 Set UserRange = ListBox1.Value ,请记住该字符串需要包含类似 Worksheets("Sheet1").Range("A1:D10") 的格式
  • 感谢您的意见!

标签: vba excel userform listboxitems


【解决方案1】:

设置 UserRange = ListBox1.Selected = True

这是分配给String 对象的错误方法。

如果您尝试从列表框中获取选定的值,那么我认为这就是您所需要的?

Dim UserRange As String

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) Then
        UserRange = ListBox1.List(i)
        Exit For
    End If
Next i

如果它是Range 对象,那么你需要将上面的内容更改为

Dim UserRange As Range

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) Then
        Set UserRange = ListBox1.List(i)
        Exit For
    End If
Next i

【讨论】:

  • 感谢您的意见!我会做出这些改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2015-09-28
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多