定义变量时出错

时间:2016-03-22 02:23:36

标签: excel vba excel-vba

大家好,我有一个单元格表,其中一列是座位号。但是,座位号包含一些字符串值,例如146A和大多数数字,例如146.但是在vba中,当我使用座位号进行vlookup时,我无法找到正确的变量,就好像我dim seatno as integer然后重视因为146A会给出错误,如果我dim seat no as string数字不起作用。我将整个座位格式化为excel中的文本,但错误仍然存​​在。因此我需要帮助我如何定义变量,该变量将显示从1到146A的所有值。这是我做过的代码

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)

   Dim answer As Integer
   answer = TextBox1.Value
   TextBox2.Value = WorksheetFunction.VLookup(answer, Sheets("L12 - Data Sheet").Range("B:E"), 2, False)
   TextBox3.Value = WorksheetFunction.VLookup(answer, Sheets("L12 - Data Sheet").Range("B:E"), 3, False)
   TextBox4.Value = WorksheetFunction.VLookup(answer, Sheets("L12 - Data Sheet").Range("B:E"), 4, False)

End Sub

1 个答案:

答案 0 :(得分:1)

如果表格中的B列(“L12 - 数据表”)绝对是文本,则将 answer 声明为字符串。

Dim answer As String
answer = TextBox1.Value
TextBox2.Value = WorksheetFunction.VLookup(answer, _
                   Sheets("L12 - Data Sheet").Range("B:E"), 2, False)

如果'L12 - 数据表'中有字符串组合(例如146A)和真数(例如146)!B:B然后将TextBox1中的值作为字符串检索尝试将其转换为真实数字。

Dim answer As String
answer = TextBox1.Value
TextBox2.Value = WorksheetFunction.VLookup(Iif(IsNumeric(answer), Int(answer), answer), _
                   Sheets("L12 - Data Sheet").Range("B:E"), 2, False)

如果“L12 - 数据表”中的值没有一致的值类型!B:B然后用你可用的所有内容点击它。

Dim answer As Variant, mtch As Long
answer = TextBox1.Value

Select Case True
    Case Not IsError(Application.Match(CStr(answer), Sheets("L12 - Data Sheet").Columns(2), 0))
        mtch = Application.Match(CStr(answer), Sheets("L12 - Data Sheet").Columns(2), 0)
    Case Not IsError(Application.Match(Int(answer), Sheets("L12 - Data Sheet").Columns(2), 0))
        mtch = Application.Match(Int(answer), Sheets("L12 - Data Sheet").Columns(2), 0)
End Select

'error control needed here in case mtch is still not a row number
debug.print mtch
TextBox2.Value = Sheets("L12 - Data Sheet").Cells(mtch, "C").Value
TextBox3.Value = Sheets("L12 - Data Sheet").Cells(mtch, "D").Value
TextBox4.Value = Sheets("L12 - Data Sheet").Cells(mtch, "E").Value