将带有计算的文本框条目输出到 Excel 工作表的 VBA 不匹配错误?

问题描述

对 VBA 来说很新,并且有一个相当简单的问题,但是数据类型一直给我带来问题。我正在 VBA 中开发多页用户窗体,并希望将用户输入输出到 Excel,在工作表中运行计算,然后在用户窗体的后续页面上提供答案。我试过在网上寻找解决方案,但没有点击。基本上尝试这个:

Sheets("Calcs").Range("DataStart").Offset(0,11).Value = CRBinQnt / 100 * Sheets("Calcs").Range("DataStart").Offset(0,6).Value

因此,用户会在文本框 CRBinQnt 中输入一个数字,我想将该数字分配给 Excel 工作表中的 Sheets("Calcs").Range("DataStart").Offset(0,11).Value。在输入该值之前,我希望将其除以 100(作为百分比)并乘以工作表 Sheets("Calcs").Range("DataStart").Offset(0,6).Value 中已有的固定值。

我尝试过 Dim CRBinQnt as long、short 等和 CDbl(CRBinQnt) 都无济于事。不知道为什么我不断收到不匹配错误。非常感激任何的帮助。刚接触这个,所以如果需要进一步说明,请告诉我。

解决方法

我要做的是使用以下代码来验证您的 TextBox df['city_enc'] = LabelEncoder().fit_transform(df['City']).astype('int8')。事件 CRBinQnt 在 TextBox 失去焦点时运行,因此我们验证其内容。

CRBinQnt_Exit

那么您应该能够使用它而不会出错。

Private Sub CRBinQnt_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Me.CRBinQnt.Value = vbNullString Then Exit Sub  ' this allows the TextBox to be left empty (if you don't want that remove it). If you don't allow it the user will be trapped in the TextBox until he enters a valid number. He even cannot abort.
    
    If Not IsNumeric(Me.CRBinQnt.Value) Then
        ' if the value is not numeric error and do not allow to leave the TextBox
        MsgBox "CRBinQnt needs to be an integer number!",vbExclamation
        Cancel = True
    ElseIf CStr(CLng(CRBinQnt.Value)) <> CRBinQnt.Value Then
        ' if the value is numeric check if it is an integer number,if not do not allow to leave the TextBox
        MsgBox "CRBinQnt needs to be an integer number!",vbExclamation
        Cancel = True
    End If
End Sub

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...