使用另一个工作表中的dynamic值填充ComboBox

—更新—

感谢您的回应,我发现DragonSamu的更新答案是完美的。


—原创post—

我一直在试图弄清楚过去几个小时我的错在哪里,但是我不能发现它。 我认为这是因为脚本正在试图从活动工作表中获取不是我想要的值。 希望有人能把我放在仪式上 – 我想答案应该是比较明显的,但我看不到它!

基本上,我试图用另一个工作表中存在的dynamic值范围来填充combobox(但是在同一个工作簿中)。 当我在工作表“材质”(这是dynamic列表的绘制位置)中运行脚本时,我可以获取combobox来填充,但是当我在工作表“产品”中运行它时,不能填充该combobox。

不幸的是,该脚本被devise为用材料填充产品,因此当“产品”工作表打开并且“材料”工作表因此将处于非活动状态时,该脚本将在用户窗体中运行。

我也应该注意到,这个脚本已经改编自我在这个论坛上其他地方find的代码,所以如果它看起来很熟悉,我预先感谢你:)

Private Sub UserForm_Initialize() Dim rRange As Range On Error GoTo ErrorHandle 'We set our range = the cell B7 in Materials Set rRange = Worksheets("Materials").Range("B7") 'Check if the cell is empty If Len(rRange.Formula) = 0 Then MsgBox "The list is empty" GoTo BeforeExit End If 'Finds the next empty row and expands rRange If Len(rRange.Offset(1, 0).Formula) > 0 Then Set rRange = Range(rRange, rRange.End(xlDown)) End If 'The range's address is our rowsource Mat1_Name_ComBox.RowSource = rRange.Address Mat2_Name_ComBox.RowSource = rRange.Address Mat3_Name_ComBox.RowSource = rRange.Address Mat4_Name_ComBox.RowSource = rRange.Address Mat5_Name_ComBox.RowSource = rRange.Address BeforeExit: Set rRange = Nothing Exit Sub ErrorHandle: MsgBox Err.Description Resume BeforeExit End Sub 

任何帮助深表感谢。

干杯,

西蒙

从我可以看到你的代码会在这里给出一个错误:

 If Len(rRange.Offset(1, 0).Formula) > 0 Then Set rRange = Range(rRange, rRange.End(xlDown)) End If 

因为你试图通过使用Range()来设置rRange而不先定义Worksheet 。 这将从ActiveWorksheet获得Range

将其更改为以下内容:

 If Len(rRange.Offset(1, 0).Formula) > 0 Then Set rRange = Worksheets("Materials").Range(rRange, rRange.End(xlDown)) End If 

最佳实践如下:

 Private Sub UserForm_Initialize() Dim wb as Workbook Dim sh as Worksheet Dim rRange As Range On Error GoTo ErrorHandle 'Set the Workbook and Worksheet set wb = Workbooks("products.xlsx") set sh = wb.Worksheets("Materials") 'We set our range = the cell B7 in Materials Set rRange = sh.Range("B7") 'Check if the cell is empty If Len(rRange.Formula) = 0 Then MsgBox "The list is empty" GoTo BeforeExit End If 'Finds the next empty row and expands rRange If Len(rRange.Offset(1, 0).Formula) > 0 Then Set rRange = sh.Range(rRange, rRange.End(xlDown)) End If 

通过正确地定义和设置您的WorkbookWorksheet您正确地引用它们并不会出错。

更新:

第二个问题是rRange.Address只将Range位置放在你的.RowSource而不是它需要看的Sheet

更改:

 Mat1_Name_ComBox.RowSource = rRange.Address 

至:

 dim strSheet as String strSheet = "Materials" Mat1_Name_ComBox.RowSource = strSheet + "!" + rRange.Address 

这样它将包含在.RowSource名称