Excel VBA无法从组合框中获取选定值

时间:2015-08-22 21:30:09

标签: vba excel-vba excel

我已经在论坛上阅读了很多关于我的问题的帖子,但我担心我仍然做错了。

今天被按钮愤怒推翻,我承认有些困惑。 我一直在尝试放置一个简单的userform组合框(frmWorkers),其中包含一个组合框(cbWorkers)并链接到一个已定义的rowSource(Workers),点击该组合将简单地获得该工作者姓名的值。 (谢谢你!) 组合框开得很好,但拒绝点击,我就停止了。

我现在收到一个编译错误,因为每个控件变量必须是变量或对象'每个WorkerName的** ...

Private Sub UserForm_Initialize()
  Dim wsControl As Worksheet
  Dim Workers As Range
  Dim WorkerName As String

  Set Workers = Range("Workers")

  **For Each WorkerName In Range("Workers")
    If WorkerName = Not Nothing Then
        Me.cbWorkers.AddItem WorkerName
    End If
  End sub

我也一直试图从ThisWorkbook中获取它,但是我得到了一个'运行时错误91,对象变量或者没有设置块变量' ** WorkerName。

Sub UsingTheScriptingRunTimeLibrary()

  Dim fso As Scripting.FileSystemObject
  Dim fileMakoret As Scripting.File, filePayroll As Scripting.File
  Dim WorkerName As String, folderPath As String, NewFolderPath As String
  Dim wsControl As Worksheet
  Dim newWbMaskoret As Workbook, wbPayroll As Workbook, wbControl As Workbook
  Dim cbWorkers As ComboBox

  Set wbControl = ActiveWorkbook
  Set wsControl = wbControl.Sheets("Control")
  **WorkerName = cbWorkers.Value

  WorkerName = Worksheets("wsControl").OLEObjects("cbWorkers").Object.Value

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

对象frmWorkerName是否有Value属性?它是什么类型的对象?

我认为您的第二个代码段的问题在于您定义cbWorkers,但您从未为其分配值。因此它的值为Nothing(在其他语言中为“null”。)

当您尝试访问cbWorkers的值时,会出现错误,因为没有对象可以访问该属性。

ETA:关于你的第二个问题:这是代码:

Dim Workers As Range
Dim WorkerName As String

Set Workers = Range("Workers")

For Each WorkerName In Range("Workers")

您收到错误是因为要执行For Each循环,变量WorkerName的类型需要与您所拥有的集合Range("Workers")的类型兼容迭代。

错误消息告诉您:如果您要在WorkerName循环中使用该Object,则需要Variant For EachRange

顺便说一下,我怀疑Excel Cell对象中的元素是简单的字符串。它们可能是WorkerName个对象,或者是具有相似名称的类型的对象。您需要将Cell转换为在循环中键入Text(或其他),然后访问其Value<button onclick="highlight('fox')+highlight('jumped')+highlight('fence')">Highlight</button> 属性。