验证选择是一个范围

Verify Selection is a Range

在 Excel(可能还有其他 Office 应用程序)中 Globals.ThisAddIn.Application.Selection 会有所不同 Type,具体取决于用户选择的内容:单元格、图表等

如何验证用户选择的单元格?

If Globals.ThisAddIn.Application.Selection.GetType Is GetType(Excel.Range) then 不起作用。问题似乎出在 GetType(Excel.Range),其中 returns :

error BC30560: 'Range' is ambiguous in the namespace 'Microsoft.Office.Interop.Excel'

有什么想法吗?


更新

源代码已更改为以下内容,以避免歧义的命名空间(如果顺便说一句,有人理解什么命名空间在这里发生冲突...?)

If Not Globals.ThisAddIn.Application.Selection.GetType Is _
   GetType(Global.Microsoft.Office.Interop.Excel.Range) Then

但是 If 语句在选择单元格时仍然无法正确运行。 即时 Window 告诉我:

?GetType(global.Microsoft.Office.Interop.Excel.Range)
{Name = "Range" FullName = "Microsoft.Office.Interop.Excel.Range"}
    [Assembly]: {MyExcelVSTO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null}
    AssemblyQualifiedName: "Microsoft.Office.Interop.Excel.Range, MyExcelVSTO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
    Attributes: Public Or ClassSemanticsMask Or Abstract Or Import {4257}
    BaseType: Nothing
    ContainsGenericParameters: False
    CustomAttributes: Count = 6
    DeclaredConstructors: {Length=0}
    DeclaredEvents: {Length=0}
    DeclaredFields: {Length=0}
    DeclaredMembers: {Length=12}
    DeclaredMethods: {Length=7}
    DeclaredNestedTypes: {System.Reflection.TypeInfo.<get_DeclaredNestedTypes>d__23}
    DeclaredProperties: {Length=5}
    DeclaringMethod: 'DirectCast(GetType(global.Microsoft.Office.Interop.Excel.Range), System.RuntimeType).DeclaringMethod' threw an exception of type 'System.InvalidOperationException'
    DeclaringType: Nothing
    FullName: "Microsoft.Office.Interop.Excel.Range"
    GUID: {00020846-0000-0000-c000-000000000046}
    GenericParameterAttributes: 'DirectCast(GetType(global.Microsoft.Office.Interop.Excel.Range), System.RuntimeType).GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'
    GenericParameterPosition: 'DirectCast(GetType(global.Microsoft.Office.Interop.Excel.Range), System.RuntimeType).GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
    GenericTypeArguments: {Length=0}
    GenericTypeParameters: {Length=0}
    HasElementType: False
    ImplementedInterfaces: {Length=1}
    IsAbstract: True
    IsAnsiClass: True
    IsArray: False
    IsAutoClass: False
    IsAutoLayout: True
    IsByRef: False
    IsCOMObject: False
    IsClass: False
    IsConstructedGenericType: False
    IsContextful: False
    IsEnum: False
    IsExplicitLayout: False
    IsGenericParameter: False
    IsGenericType: False
    IsGenericTypeDefinition: False
    IsImport: True
    IsInterface: True
    IsLayoutSequential: False
    IsMarshalByRef: False
    IsNested: False
    IsNestedAssembly: False
    IsNestedFamANDAssem: False
    IsNestedFamORAssem: False
    IsNestedFamily: False
    IsNestedPrivate: False
    IsNestedPublic: False
    IsNotPublic: False
    IsPointer: False
    IsPrimitive: False
    IsPublic: True
    IsSealed: False
    IsSecurityCritical: False
    IsSecuritySafeCritical: False
    IsSecurityTransparent: True
    IsSerializable: False
    IsSpecialName: False
    IsUnicodeClass: False
    IsValueType: False
    IsVisible: True
    MemberType: TypeInfo {32}
    MetadataToken: 33554450
    [Module] (System.Reflection.MemberInfo): {MyExcelVSTO.dll}
    [Module]: {MyExcelVSTO.dll}
    Name: "Range"
    [Namespace]: "Microsoft.Office.Interop.Excel"
    ReflectedType: Nothing
    StructLayoutAttribute: Nothing
    TypeHandle: {System.RuntimeTypeHandle}
    TypeInitializer: Nothing
    UnderlyingSystemType: {Name = "Range" FullName = "Microsoft.Office.Interop.Excel.Range"}


?Globals.ThisAddIn.Application.Selection.GetType
{Name = "__ComObject" FullName = "System.__ComObject"}
    [Assembly]: {mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089}
    AssemblyQualifiedName: "System.__ComObject, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    Attributes: Public {1}
    BaseType: {Name = "MarshalByRefObject" FullName = "System.MarshalByRefObject"}
    ContainsGenericParameters: False
    CustomAttributes: Count = 1
    DeclaredConstructors: {Length=1}
    DeclaredEvents: {Length=0}
    DeclaredFields: {Length=1}
    DeclaredMembers: {Length=11}
    DeclaredMethods: {Length=9}
    DeclaredNestedTypes: {System.Reflection.TypeInfo.<get_DeclaredNestedTypes>d__23}
    DeclaredProperties: {Length=0}
    DeclaringMethod: 'DirectCast(Globals.ThisAddIn.Application.Selection.GetType, System.RuntimeType).DeclaringMethod' threw an exception of type 'System.InvalidOperationException'
    DeclaringType: Nothing
    FullName: "System.__ComObject"
    GUID: {00000000-0000-0000-0000-000000000000}
    GenericParameterAttributes: 'DirectCast(Globals.ThisAddIn.Application.Selection.GetType, System.RuntimeType).GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'
    GenericParameterPosition: 'DirectCast(Globals.ThisAddIn.Application.Selection.GetType, System.RuntimeType).GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
    GenericTypeArguments: {Length=0}
    GenericTypeParameters: {Length=0}
    HasElementType: False
    ImplementedInterfaces: {Length=0}
    IsAbstract: False
    IsAnsiClass: True
    IsArray: False
    IsAutoClass: False
    IsAutoLayout: True
    IsByRef: False
    IsCOMObject: True
    IsClass: True
    IsConstructedGenericType: False
    IsContextful: False
    IsEnum: False
    IsExplicitLayout: False
    IsGenericParameter: False
    IsGenericType: False
    IsGenericTypeDefinition: False
    IsImport: False
    IsInterface: False
    IsLayoutSequential: False
    IsMarshalByRef: True
    IsNested: False
    IsNestedAssembly: False
    IsNestedFamANDAssem: False
    IsNestedFamORAssem: False
    IsNestedFamily: False
    IsNestedPrivate: False
    IsNestedPublic: False
    IsNotPublic: False
    IsPointer: False
    IsPrimitive: False
    IsPublic: True
    IsSealed: False
    IsSecurityCritical: False
    IsSecuritySafeCritical: False
    IsSecurityTransparent: True
    IsSerializable: False
    IsSpecialName: False
    IsUnicodeClass: False
    IsValueType: False
    IsVisible: False
    MemberType: TypeInfo {32}
    MetadataToken: 33554625
    [Module] (System.Reflection.MemberInfo): {CommonLanguageRuntimeLibrary}
    [Module]: {CommonLanguageRuntimeLibrary}
    Name: "__ComObject"
    [Namespace]: "System"
    ReflectedType: Nothing
    StructLayoutAttribute: {System.Runtime.InteropServices.StructLayoutAttribute}
    TypeHandle: {System.RuntimeTypeHandle}
    TypeInitializer: Nothing
    UnderlyingSystemType: {Name = "__ComObject" FullName = "System.__ComObject"}

首先检查您的参考资料。

当我包含对 Microsoft.Office.Interop.ExcelMicrosoft office 15.0 object library 的引用时,我能够看到问题。后来我只尝试了第一个。问题消失了。

如果引用没有问题,那么按照下面的方法尝试。

首先获取活动作品的对象sheet。

然后使用工作sheet对象检查选择

Dim wsSheet As Excel.Worksheet = CType(Globals.ThisWorkbook.ActiveSheet, Excel.Worksheet)    

If wsSheet.Cells.Application.Selection.GetType Is GetType(Excel.Range) Then

End If

另一种方法是创建一个 IsRange 函数并捕获任何 system.InvalidCastException,即 Exception thrownType,当 VB 试图将 Selection 转换为 Excel.Range.

例如:

''' <summary>
''' Returns a <see cref="Boolean"/> value indicating wether a selection is a <see cref="Excel.Range"/> Object.
''' </summary>
''' <param name="Selection">If not provided, ThisAddIn.Application.Selection is used by default.</param>
''' <returns></returns>
Private Function IsRange(ByVal Optional Selection As Object = Nothing) As Boolean
    If Selection Is Nothing Then Selection = Globals.ThisAddIn.Application.Selection
    Try
        Dim MyRange As Excel.Range = Selection
    Catch ex As system.InvalidCastException
        Return False
    End Try
    Return True
End Function