【问题标题】:Set Currently Selected Cells as the Range to Process将当前选定的单元格设置为要处理的范围
【发布时间】:2018-11-12 14:02:26
【问题描述】:

我正在使用 Visual Studio 构建一个 Excel 插件并将我的 Excel VBA 代码转换为 VB.Net 代码。

我不知道如何通过插件在 Excel 中选择的单元格上运行宏。

此代码在单元格 A1 上执行。如何将其更改为适用于所有选定的单元格?

Imports Microsoft.Office.Tools.Ribbon
Imports Microsoft.Office.Interop.Excel

Public Class Ribbon1

    Private Sub Ribbon1_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load

    End Sub

    Private Sub BtnFontToggle_Click(sender As Object, e As RibbonControlEventArgs) Handles BtnFontToggle.Click

            Dim ActiveWorksheet As Microsoft.Office.Interop.Excel.Worksheet =
            Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets(1)

            Dim Worksheet As Microsoft.Office.Tools.Excel.Worksheet =
            Globals.Factory.GetVstoObject(ActiveWorksheet)

        Dim CurrentColor
        Dim Selection As Excel.Range = Worksheet.Range("A1")

'******* Instead of selecting cell A1, I want the code to select all active cells (those that are currently highlighted)*****

        'What is the current font color?
        CurrentColor = Selection.Font.ColorIndex

        'Change font color based on current font color
        'Order Black, Blue, Green, Red
        If CurrentColor = 1 Then
            Selection.Font.ColorIndex = 5
        Else
            If CurrentColor = 5 Then
                Selection.Font.ColorIndex = 10
            Else
                If CurrentColor = 10 Then
                    Selection.Font.ColorIndex = 3
                Else
                    If CurrentColor = 3 Then
                        Selection.Font.ColorIndex = 1
                    Else
                        Selection.Font.ColorIndex = 1
                    End If
                End If
            End If
        End If
    End Sub
End Class

​

【问题讨论】:

    标签: excel vb.net visual-studio


    【解决方案1】:

    您应该能够使用Application.Selection Property 来确定当前是否选择了 Excel.Range,如果是,则检索它。请注意,当前选择可能是其他对象,例如 ChartArea。选择属性返回类型Object,因此使用TryCast 尝试转换为Excel.Range。如果转换失败,TryCast 返回Nothing

    Dim Selection As Excel.Range = TryCast(Globals.ThisAddIn.Application.Selection, Excel.Range)
    If Selection IsNot Nothing Then
       ' you retrieved a Range object
    End If
    

    【讨论】:

    • 这成功了!非常感谢 TnTinMn 和您的解释。
    猜你喜欢
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多