新手,仅在24小时左右完成。其中12个小时一直在研究这个问题。我发现这么多页面的例子似乎都应该可以使用,但是还没有。我一定很遗憾,显而易见。
我的代码:
问题是vlookup。我得到"运行时错误1004:无法获取WorksheetFunction类的#eleookup属性"。
我知道我的变量 Prodcode 包含正确的工作表名称(C1), ForecastYear 包含正确的年份(2016.1)。我认为我的问题是我没有以某种方式引用工作表名称,但我试图关注来自这么多网站的示例,但没有一个能够运作。
Function WorksheetExists(WSName As String) As Boolean
On Error Resume Next
WorksheetExists = Worksheets(WSName).Name = WSName
On Error GoTo 0
End Function
Private Sub UserForm_Initialize()
Dim ProdCode As String
Do Until WorksheetExists(ProdCode)
ProdCode = InputBox("Enter Product Code: ", "Enter Product Code:", "i.e C1")
If Not WorksheetExists(ProdCode) Then MsgBox ProdCode & _
" doesn't exist!", vbExclamation
Loop
Sheets(ProdCode).Select
Me.Title.Caption = "Forecast data for " & ProdCode
Me.Label2012.Caption = Format(Now(), "yyyy")
Me.Label1sta.Caption = "1st Qtr"
Me.Label2nda.Caption = "2nd Qtr"
Me.Label3rda.Caption = "3rd Qtr"
Me.Label4tha.Caption = "4th Qtr"
Me.LabelFc1.Caption = "Forecast"
Me.Labelwfc1.Caption = "Weighted Forecast"
Me.LabelwD1.Caption = "Weighted Demand"
'-----------------------------------------------------------------------------
'1st quarter current year predictions
Dim ForecastYear As Double
ForecastYear = Year(Now) + .1 'the .1 is to break the year into quarters
MsgBox (ForecastYear) 'for debugging only. checks the correct year is selected
MsgBox (ProdCode) 'for debugging only. checks the correct worksheet is selected
Dim Forecast As Double
Forecast = Application.WorksheetFunction.VLookup(ForecastYear, _
Sheets(ProdCode).Range("A9:J5000"), 10, False)
Forecast = Round(Forecast, 2)
'-----------------------------------------------------------------------------
With ListBox1
.AddItem ForecastYear
.AddItem Forecast
.AddItem ""
End With
End Sub
对不起,我知道之前可能会有人问过这个问题。我甚至可能在另一页上盯着答案而没有意识到这是答案。
答案 0 :(得分:1)
我想你必须改变:
Dim Forecast As Double
Forecast = Application.WorksheetFunction.VLookup(ForecastYear, Sheets("ProdCode").Range("A9:J5000"), 10, False)
Forecast = Round(Forecast, 2)
'-----------------------------------------------------------------------------
With ListBox1
.AddItem ForecastYear
.AddItem Forecast
.AddItem ""
End With
为:
Dim Forecast As Variant
Forecast = Application.VLookup(ForecastYear, Sheets(ProdCode).Range("A9:J5000"), 10, False)
If IsError(Forecast) Then
MsgBox "couldn't find '" & ForecastYear & "' in Sheets '" & ProdCode & "'"
Exit Sub
End If
Forecast = Round(Forecast, 2)
'-----------------------------------------------------------------------------
With ListBox1
.AddItem ForecastYear
.AddItem Forecast
.AddItem ""
End With
此外,我将最初的ProdCode
循环重构为:
ProdCode = Application.InputBox("Enter Product Code: ", "Enter Product Code:", "i.e C1", , , , , 2)
Do While Not WorksheetExists(ProdCode)
MsgBox ProdCode & " doesn't exist!", vbExclamation
ProdCode = Application.InputBox("Enter Product Code: ", "Enter Product Code:", "i.e C1", , , , , 2)
Loop