Excel VBA错误:1004当selectvariables值的范围时,对象“_Worksheet”的方法“范围”失败

我的问题:当试图Set Table = cSheet.Range(brand_edit) (brand_edit是一个表名的值的variables)我得到运行时错误'1004':对象'_WorkSheet'的方法'范围'失败。

我想这是因为我试图find一个variables的值的范围,我想不出一种方法来解决这个问题。

更多信息:

我正在制作一个用户窗体 ,允许用户从Excel中的数据表中获取项目ID,并使用项目ID导向的行中的数据填充表格/项目列表。

我已经设置了一个combobox,从数据表中抓取我的目录(品牌)(我把它制成一张表,并使用表格作为行来源)。 然后我设置另一个combobox,显示所选品牌的商品ID。 当你select一个特定的ID时,我试图把它从表格中那个Item ID所在行的数据中获取。

每个品牌有一个表绑定它我用一些时髦的replace,以使其匹配表命名scheme。 我使用这些表作为灵活的范围(这些表将随着时间的推移而改变,所以我需要考虑这一点)。 商品ID引导行,每行都有关于商品的信息(成本,描述等)

如果有更好的办法做这些事情,我愿意接受。

用户表单

以下是我想要解决的一些问题:这个问题向我介绍了这个代码,并且尝试了解我的用例,并且发现了错误。 Excel VBA – select,获取和设置表中的数据

 Public brand_edit As String Private Sub cmbItemID_Change() Dim cBook As Workbook Dim cSheet As Worksheet Dim ItemID As String Dim Brand_Table As String Dim test As String Dim i As Long Dim Table As ListObject Set cBook = ActiveWorkbook Set cSheet = cBook.Sheets("Gen. Info") ItemID = cmbItemID.Value Brand_Table = brand_edit MsgBox Brand_Table Set Table = cSheet.Range(brand_edit).Select For i = 1 To Table.ListRows.Count If Table.ListColumns(1).DataBodyRange.Rows(i) = ItemID Then MsgBox ItemID End If Next MsgBox test End Sub Public Sub cmbItemID_DropButtonClick() 'funky replacing Dim brand As String brand = cmbBrand.Value brand_edit = Replace(brand, " ", "_") brand_edit = Replace(brand_edit, """", "") brand_edit = Replace(brand_edit, "-", "") brand_edit = Replace(brand_edit, "__", "_") brand_edit = LCase(brand_edit) cmbItemID.RowSource = brand_edit End Sub 

有一个更好的方法来同步ComboBoxes! 没有编码! 在这里输入图像说明
两个ComboBox都有相同的数据设置设置。 他们在共享LinkedCell中设置相同的值。 1. BoundColumn 2. LinkedCell 3. ListFillRange 在这里输入图像说明 但是我们改变他们的显示设置给用户一个不同的看法。 1. ColumnCount 2. ColumnWidths 3. ListRows 4. ListWidth 在这里输入图像说明

您不能直接将ListFillRange设置为表。 解决方法是创build一个定义名称并将ListFillRange设置为新名称。

ListFillRange – > Products – > Table1

在这里输入图像说明

所以我解决了这个问题。 是什么原因导致我正在引用错误的表格(又名Gen. Info)。 我如何解决这个问题:

 Set dSheet = cBook.Sheets("DATA") Set Table = dSheet.Range(brand_edit) 

当然,一旦一个问题得到解决,另一个问题就会出现 所以我正在努力解决这个问题。

这篇文章阅读了好几次(昨天发布前的几个小时,然后今天上午几次),我Finnaly得到了什么,帮助我解决了这个问题。 VBA方法'对象范围'_Worksheet在运行代码时突然出现失败?

希望这是更有用的。

将getRowSource放置在公共模块中。 testing和扩展会更容易。

 Public Function getRowSource(brand As String) As String brand = Replace(brand, " ", "_") brand = Replace(brand, """", "") brand = Replace(brand, "-", "") brand = Replace(brand, "__", "_") brand = LCase(brand) getRowSource = brand End Function 

这样,您可以在即时窗口中testing您的行源逻辑

在这里输入图像说明

如果cmbItemID的RowSource是要引用的表,那么cmbItemID的ListIndex就是你想要引用的行。

 Dim itemIndex As Long, brand_edit As String brand_edit = getRowSource(cmbBrand.Value) itemIndex = cmbItemID.ListIndex With cSheet.ListObjects(brand_edit) TextBoxListPrice.Value = DataBodyRange(itemIndex, 1) TextBoxListCost.Value = DataBodyRange(itemIndex, 2) TextBoxNotes.Value = DataBodyRange(itemIndex, 3) TextBoxSpecs.Value = DataBodyRange(itemIndex, 4) TextBoxDescription.Value = DataBodyRange(itemIndex, 5) End With