尝试在excel vba中使用输入框

时间:2017-05-12 03:27:59

标签: excel vba excel-vba

我正在尝试使用输入框在我的代码中使用值,但是当我添加它时它会开始给我提供错误。

Sub pipe_size()

Dim x As Variant
Dim y As Variant
Dim NPS As Variant
Dim Sch As Variant
Dim z As Single
Dim i As Single
Dim a As Variant
Dim j As Integer
Dim msg As String
Dim b As Variant

'NPS = InputBox("Enter Nominal Pipe Size(inches)", "Nominal Pipe Size")
'Sch = InputBox("Enter Schedule Number", "Pipe Schedule")

NPS = Worksheets("Sheet2").Range("R35").Value
Sch = Worksheets("Sheet2").Range("R36").Value
'x is column number, y is row number
x = Application.WorksheetFunction.Match(NPS, Worksheets("Sheet2").Range("Q5:Q33"), 0)
y = Application.WorksheetFunction.Match(Sch, Worksheets("Sheet2").Range("R3:AD3"), 0)

'Worksheets("Sheet2").Range("Y34").Value = Sch
'Worksheets("Sheet2").Range("Y35").Value = x
'Worksheets("Sheet2").Range("Y36").Value = y

Worksheets("Sheet2").Range("AI1:AI13").Clear
Worksheets("Sheet1").Range("E4").Clear

For i = 1 To 13
a = Application.WorksheetFunction.Index(Worksheets("Sheet2").Range("R5:AD33"), x, i)
If a > 0 Then
Worksheets("Sheet2").Range("AI" & i).Value = Application.WorksheetFunction.Index(Worksheets("Sheet2").Range("R3:AD33"), 1, i)
Else: End If
Next i

z = Application.WorksheetFunction.Index(Worksheets("Sheet2").Range("R5:AD33"), x, y)
If z > 0 Then
Worksheets("Sheet2").Range("Y37").Value = z
Worksheets("Sheet1").Range("E4").Value = z
ElseIf z = 0 Then
MsgBox ("This pipe schedule does not exist for this pipe size")
msg = "The following schedules exist for this pipe size:" & vbCrLf

For j = 1 To 13
b = Worksheets("Sheet2").Range("AI" & j)
If b > 0 Then
msg = msg & vbCrLf & b

Else: End If

Next j

MsgBox msg

Else: End If


End Sub

当代码从单元格中获取NPS和Sch的值时,代码运行正常但是当我尝试使用输入框来给出值时,它会在工作簿函数中找到类型不匹配和错误。

1 个答案:

答案 0 :(得分:0)

使用如下的Application.InputBox ......

NPS = Application.InputBox("Enter Nominal Pipe Size(inches)", "Nominal Pipe Size", Type:=1) 'Type:=1 means Numeric input
Sch = InputBox("Enter Schedule Number", "Pipe Schedule", Type:=2) 'Type:=2 means String input

根据您的要求更改类型。

OR

您可以使用Range.Find,如下所示......

Dim rng As Range
Sch = Application.InputBox("Enter Schedule Number", "Pipe Schedule", Type:=2)
Set rng = Worksheets("Sheet2").Range("R3:AD3").Find(Sch)
If Not rng Is Nothing Then
    y = rng.Column - 17
    MsgBox y
End If