【问题标题】:excel truncating very large integers pulled from htmlexcel截断从html中提取的非常大的整数
【发布时间】:2017-05-06 03:29:17
【问题描述】:

我有一个 VBA 脚本,它成功地从 html 中提取数据并将其转储到 Excel 工作表中。当某些数据是一个非常大的整数(30 位 + 数字)时,我的问题会出现,Microsoft excel 默认将其存储为科学记数法并且我遭受数据丢失。
所以数据是这样存储在html中的:

<tr>
<td>
      11111111111111111111111111
</td>
</tr>  

所以我的脚本循环遍历行 (tr) 并为每个单元格 (td) 将值拉到我的工作表中,如下所示:

Set mydata = appIE.Document.getelementsbytagname("tr")
x=1
        For Each e In mydata
            Set mytd = e.getelementsbytagname("td")
            For Each c In mytd

                    Cells(x, 2).Value2 = e.Cells(1).innerText
                    x = x + 1

            Next c
        Next e  

所以我认为发生错误是因为我使用 .value2 将数据存储在我的单元格中,所以我尝试切换到重现错误的 .value 和无法运行的 .text。如何在不丢失数据的情况下正确将此数据类型设置为 long 或 text?

【问题讨论】:

  • 您永远不会在 For each 循环中使用 c。你的意思是?
  • Excel 最多只能处理 15 位的精度。如果您有大量数字并希望它们准确表示,请将单元格格式设置为文本,然后填充该值。
  • 感谢 cmets。我删除了一些 c 的私有代码行,忘记了 :) 猜我会使用文本!

标签: html vba excel


【解决方案1】:

在 Excel VBA 中您能做的最好的事情是使用变体并显式声明 Decimal 类型转换。这允许存储多达 29 位数字(我只使用 1 对此进行了测试。其他数字也不重要,但把它放在那里)。

你会想做这样的事情:

Sub Test()
    Dim InputString As String
    Dim DecimalHolder As Variant

    ' Put the string representation of your number into a string variable
    ' For my purposes, this was mostly to verify the input since the editor
    ' will convert this number to Scientific Notation otherwise.
    InputString = "11111111111111199999999999999"

    ' Using the variant variable, store the number by converting the string to a decimal.
    DecimalHolder = CDec(InputString)

    ' This now works, and is accurate
    DecimalHolder = DecimalHolder + 1
End Sub

如果您输入的任何数字超过 29 个字符,您将需要创建一种方法将它们修剪到 29 个字符的限制。如果不这样做,在尝试将数字存储在 DecimalHolder 变量中时会出现溢出错误。

所有这一切的原因是 VBA 授予每种数据类型的字节数。我们在这里使用变体,因为变体有 16 个字节可供使用(转换为十进制时减少到 12 个字节),而 double 类型有 8 个,long 类型有 4 个,int 类型有 2 个。

如果最终您不需要数字,但您需要数字的字符表示(例如,如果这些“数字”用于 Id 的功能),那么您可以将数字存储为字符串。您将无法在不转换的情况下对字符串进行数字运算(尽管隐式转换可能只是这样做,而不是告诉您)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2014-01-19
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多