C# 将 VBA 宏转换为具有自定义 RGB 颜色的 C#

标签 c# vba ms-word rgb office-automation

在将 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)

使用 Office.Interop 命名空间转换为 C#:

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);

This question使用相同的方法。但看起来还是太复杂了...

更新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);
}

最佳答案

您在 VBA 代码中实际调用的 RGB 函数位于 VBA 标准库的 Information 模块中 - 至少根据 Rubberduck 2.0的上下文相关状态栏(免责声明:我编写了该功能):

Rubberduck 2.0's context-sensitive status bar

RGB 函数实际上只是接收 3 个数字并输出相应的 RGB 十六进制值。

This question具体询问如何从 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();

关于C# 将 VBA 宏转换为具有自定义 RGB 颜色的 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990224/

相关文章:

c# - 从 PDF 中的嵌套表格中提取数据

c# - 如何找到带有 params 参数的方法的用法,以使参数不为空?

c# - 了解 C# 5 异步/等待中的上下文

excel - 有没有办法在VBA中使用selenium,获取url,而不打开浏览器?

vba - 非 ActiveSheet 范围内的 QueryTables

java - 我如何将 MS Word 的书签导入并读取到 Java

xpath - 我正在使用 docx4j 来读取 .docx 文件,我需要获取文档的段落并替换字符串

C# Sql 跨页面连接字符串

c# - Linq To XML、yield 等

excel - 如果单元格的值等于另一列的任何值,则对单元格进行条件格式设置