将当前选定的单元格设置为要处理的范围

时间:2018-06-02 18:57:36

标签: excel vb.net visual-studio

我正在使用Visual Studio构建Excel Addin并将我的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

​

1 个答案:

答案 0 :(得分:0)

您应该能够使用Application.Selection Property来确定当前是否选择了Excel.Range,如果是,则检索它。请注意,当前选择可能是某些其他对象,如ChartArea。 Selection属性返回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