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)
我只想动态选择工作表中的第一列。
答案 0 :(得分: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")*
答案 1 :(得分:0)
请使用以下 isNameRngExist 函数,当名称范围“DrugCodeInventory”存在时,该函数将返回true,然后您可以继续进行进一步操作。
Function isNameRngExist(myRng As String) As Boolean
On Error Resume Next
isNameRngExist = Len(ThisWorkbook.Names(TheName).Name) <> 0
End Function