1
Private Sub Submit_Click()
Application.ScreenUpdating = False

Dim rangeForCode As range, rngLookupRange As range

Dim row As Integer, stock As Integer
Dim result As Integer
Dim drugCodePC As Integer
Dim qty As Integer
Dim ws As Worksheet

drugCodePC = CInt(DrugCode2.Value)
qty = CInt(Quantity.Value)

'Populating the drug name
Set ws = Worksheets("Drug Record")
ws.Select

*Set rangeForCode = ws.range("DrugCodeInventory")*
row = Application.WorksheetFunction.Match(drugCodePC, rangeForCode, 1)
Set rngLookupRange = ws.range("Inventory")
stock = Application.WorksheetFunction.VLookup(drugCodePC, rngLookupRange, 3, False)
result = stock + qty
'MsgBox (row)
ws.Cells(row + 1, 3).Value = result

Application.ScreenUpdating = True
Unload PurchaseForm 
End Sub

这不断抛出错误“对象_worksheet的方法范围失败命名范围”。错误发生在**。我知道这与命名的范围有关,因为以前,当我编写单元格范围时,即。“A1:A215”它有效。我检查了名称范围,它看起来正确。命名范围的名称也是正确的。我尝试先激活工作簿,但仍然抛出错误。

命名的范围是:

= OFFSET(DrugCodeInventory!$A$2, 0, 0, COUNTA(DrugCodeInventory!$A:$A)-1,1)

我只想动态选择工作表中的第一列。

4

2 回答 2

0

如果您在“立即”窗口中运行它,它会起作用吗?

application.Goto Worksheets("Drug Record").range("DrugCodeInventory")

如果它没有运行,请尝试删除命名范围并创建一个新范围。

还请尝试明确限定代码的这一部分:

Dim ws As Excel.Worksheet '<added full qualification here

drugCodePC = CInt(DrugCode2.Value)
qty = CInt(Quantity.Value)

'Populating the drug name
Set ws = Excel.thisworkbook.Worksheets("Drug Record") '<added full qualification here
ws.Select

*Set rangeForCode = ws.range("DrugCodeInventory")*
于 2013-03-23T20:03:57.023 回答
0

请使用以下isNameRngExist函数,当名称范围“DrugCodeInventory”存在时,该函数将返回 true,然后您可以继续进行进一步操作。

Function isNameRngExist(myRng As String) As Boolean
    On Error Resume Next
    isNameRngExist = Len(ThisWorkbook.Names(TheName).Name) <> 0
End Function
于 2013-03-24T03:42:48.050 回答