尝试在Excel VBA中使用input框

我试图让我的代码使用input框中使用的值,但它开始给我错误,当我join这个。

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的值时,代码运行正常,但是当我尝试使用input框来给出值时,它会在工作簿函数中发现types不匹配和错误。

像下面的使用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 

根据您的要求更改types。

要么

你可以使用下面的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