简体   繁体   English

使用VBA在Excel中将单元格的值/格式转换为HTML字符串

[英]Convert a Cell's Value/Formats to an HTML String in Excel with VBA

I have had this issue in multiple applications now and I am wondering if anyone has come up with a more efficient solution than mine. 我现在在多个应用程序中都遇到了这个问题,我想知道是否有人提出了比我更有效的解决方案。 Essentially, my goal is to convert the content within a cell, to an HTML string to include all of its formatting. 本质上,我的目标是将单元格中的内容转换为HTML字符串以包括其所有格式。 My workaround up to this point has been to loop through each character in the string to determine the font size, weight, and style, however, this can prove to be extremely slow when converting a lot of data at once. 到目前为止,我的解决方法是循环遍历字符串中的每个字符以确定字体大小,粗细和样式,但是,一次转换大量数据时,这可能会非常慢。

Going through each character in turn will be very slow, but should only be necessary in extreme cases. 依次浏览每个字符将非常缓慢,但是仅在极端情况下才需要。 I've tackled this same problem quite successfully using the following method. 我已经使用以下方法成功解决了相同的问题。

For each relevant property (bold, italic, etc.) I build up an array that stores the position of each change in the value of that property. 对于每个相关属性(粗体,斜体等),我建立一个数组来存储该属性值中每个更改的位置。 Then when generating the HTML, I can spit out all the text up until the next change (in any property). 然后,在生成HTML时,我可以吐出所有文本,直到进行下一次更改(在任何属性中)。 Where changes are infrequent, this is clearly faster. 如果不经常进行更改,这显然会更快。

Now, to arrive at the position of the changes in each property, I first test whether there are in fact any changes, and this is easy - for example, Font.Bold will return true if all the text is bold, false if it's all non bold, and null (or some other value - I can't remember) if there are both bold and non-bold parts. 现在,要确定每个属性中更改的位置,我首先测试实际上是否存在任何更改,这很容易-例如,如果所有文本均为粗体,Font.Bold将返回true,如果全部为false,则返回false。非粗体部分,如果有粗体部分和非粗体部分,则为null(或其他值-我不记得了)。

So, if there's no change in the value at all, we're done already. 因此,如果值没有任何变化,那么我们已经完成了。 If there is a change in the value, then I do a binary sub-division of the text into two halves and start again. 如果值有变化,则将文本进行二进制细分,分为两半,然后重新开始。 Again, I might find that one half is all the same, and the other half contains a change, so I do another sub-division of the second half as before, and so on. 同样,我可能会发现一半完全相同,而另一半包含更改,因此我像以前一样对后半部分进行了另一个细分,依此类推。

Since very few cells tend to have lots of changes, and many have none at all, this ends up being quite efficient. 由于很少有单元趋向于进行大量更改,而许多单元根本没有任何更改,因此最终效率很高。 Or at least much more efficient than the character by character method. 或者至少比逐字符方法更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM