在将VBA宏转换为用C#编码的插件时,我遇到了以下僵局。
原始的VBA代码是:
Selection.Font.Name = "Times New Roman"
Selection.Font.Size = 14
Selection.Font.Bold = True
Selection.Font.BoldBi = True
Selection.Shading.Texture = wdTextureNone
Selection.Shading.ForegroundPatternColor = wdColorAutomatic
Selection.Shading.BackgroundPatternColor = RGB(173, 216, 230)
转换为具有C#命名空间的Office.Interop
:
using Microsoft.Office;
using Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;
Word.Document oWordDoc = new Word.Document();
var Selection = oWordDoc.ActiveWindow.Selection;
Selection.Font.Name = "Times New Roman";
Selection.Font.Size = 14;
Selection.Shading.Texture = Word.WdTextureIndex.wdTextureNone;
Selection.Shading.ForegroundPatternColor = Word.WdColor.wdColorAutomatic;
Selection.Shading.BackgroundPatternColor = Word.ColorFormat.RGB(173, 216, 230);
这段代码不会编译,因为RGB
不是一个方法。我正试图找出如何使用可用的方法来实现这一点,但到目前为止还没有成功。
我希望有任何关于这个或任何描述的意见来解释转换。
更新:
实际上,它看起来像下面的工作:
Color mycolor = Color.FromArgb(173, 216, 230);
Selection.Shading.BackgroundPatternColor = (Word.WdColor)(mycolor.R + 0x100 * mycolor.G + 0x10000 * mycolor.B);
这个问题使用同样的方法。但看起来还是太复杂了..。
更新2:
根据下面的建议,这似乎是最顺利的方法:
Selection.Shading.BackgroundPatternColor = RGB(172,216,230);
private Word.WdColor RGB(int p1, int p2, int p3)
{
return (Word.WdColor)p1 + (0x100 * p2) + (0x10000 * p3);
}
发布于 2016-05-02 20:13:41
您在VBA代码中实际调用的RGB
函数位于VBA标准库中的Information
模块中--至少根据Rubber达克2.0的上下文敏感状态栏(免责声明:我编写了该特性):
这个RGB
函数实际上只做了3个数字,并输出了相应的RGB十六进制值。
这个问题专门询问如何将System.Drawing.Color
转换为WdColor
值--并且所接受的答案看起来与您的“太复杂”代码非常相似。另一个解决方案是导入Microsoft.VisualBasic
并使用相同的Information.RGB
函数..。但是,每当我看到Microsoft.VisualBasic
在.NET项目中的任何地方导入时,我都会畏缩不前--它散发着做错事的臭味。
相反,您可以创建一个简单的扩展方法:
using System.Drawing;
using Microsoft.Interop.Word;
static class ColorExtensions
{
public static WdColor ToWdColor(this Color color)
{
return (WdColor)(color.R + 0x100 * color.G + 0x10000 * color.B);
}
}
它将您的代码转换为:
var color = Color.FromArgb(173, 216, 230).ToWdColor();
发布于 2016-05-02 20:16:51
若要从RGB十进制设置颜色:
Selection.Shading.BackgroundPatternColor = (Word.WdColor)(173 + 216 * 256 + 230 * 65536);
来自RGB十六进制:
Selection.Shading.BackgroundPatternColor = (Word.WdColor)0x00E6D8AD;
https://stackoverflow.com/questions/36990224
复制相似问题