【问题标题】:VBA test format of text/value文本/值的VBA测试格式
【发布时间】:2018-08-07 12:39:03
【问题描述】:

我正在制作一个子程序,将 DXF 文件作为文本导出到我的工作表中,然后从中取出一些值。

我有两个问题:
--> 首先是如何保持我在工作表中导出的值的格式?
--> 第二个是如何测试值的格式?

我要导出的文件中有不同类型的值:

  • 文字
  • 整数“10”、“20”、“21”等。它告诉我后面会出现什么样的值
  • 我想要的实际值(由整数给出),写为 xxx.xxxx(例如“0.0000”、“50.0000”或 120.0000,所以点后总是有 4 个零) 在文件中它看起来像这样:

    连续
    10
    50.0000
    20
    120.0000
    30
    0.0000
    40
    50.0000
    50
    0.0000
    51
    180.0000
    62
    5
    0

所以我的问题是,当我导出它时,excel 并没有保持我的值。如果它是 50.0000 它会写 50 然后我无法区分值的类型......我找到的所有解决方案都是关于将我的所有数据作为格式 #.000 但这并不能解决我的问题.. .

这是我的潜艇:

Sub ImportDXF()
Dim fName As String
ActiveSheet.Columns(1).ClearContents

fName = Application.GetOpenFilename("DXF Files (*.dxf), *.dxf")
If fName = "False" Then Exit Sub
Dim v As Variant
Dim r As Long
r = 2 'from row 2

Open fName For Input As #1
Do While Not EOF(1)
    Input #1, Line$
    Rows(r).Columns(1) = Trim(Line$)
    r = r + 1
Loop
Close #1
End Sub  

然后我有另一个 sub 可以用我导出的值做一些事情,所以我想测试这是一个整数值还是一个浮点数..

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    您必须在从输入 DXF 文件中读取每个值时对其进行测试。然后,对具有该值的单元格应用适当的格式,以便它在您的电子表格中正确显示。

    Sub ImportDXF()
        Dim fName As String
        ActiveSheet.Columns(1).ClearContents
    
        fName = Application.GetOpenFilename("DXF Files (*.dxf), *.dxf")
        If fName = "False" Then Exit Sub
        Dim v As Variant
        Dim r As Long
        r = 2                                        'from row 2
    
        Open fName For Input As #1
        Do While Not EOF(1)
            Input #1, Line$
            If IsNumeric(Line$) Then
                '--- we have a number, but what kind?
                If InStr(1, Line$, ".", vbTextCompare) > 0 Then
                    '--- we have a VALUE, so format to show the decimals
                    Cells(r, 1).NumberFormat = "#0.0000"
                Else
                    '--- we have a value ID, format with no decimals
                    Cells(r, 1).NumberFormat = "#0"
                End If
            Else
                '--- we have text
                Cells(r, 1).NumberFormat = "@"
            End If
            Cells(r, 1).Value = Trim(Line$)
            r = r + 1
        Loop
        Close #1
    End Sub
    

    【讨论】:

    • 非常感谢!我不知道为什么我之前没有考虑在字符串中搜索点...
    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2020-06-14
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多