Проверить выбор это диапазон - PullRequest
0 голосов
/ 18 февраля 2019

В Excel (и, вероятно, других приложениях Office) Globals.ThisAddIn.Application.Selection будет различаться Type, в зависимости от того, что выбрал пользователь: ячейки, диаграммы и т. Д.

Как проверить выбранные пользователем ячейки?

If Globals.ThisAddIn.Application.Selection.GetType Is GetType(Excel.Range) then не работает.Кажется, проблема связана с GetType(Excel.Range), который возвращает:

ошибка BC30560: «Диапазон» неоднозначен в пространстве имен «Microsoft.Office.Interop.Excel»

Любые идеи?


Обновление

Исходный код был изменен на следующее, чтобы избежать неоднозначного пространства имен (если, кстати, кто-то понимает, что пространство имен конфликтует здесь ...?)

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

Но оператор If по-прежнему не может работать правильно, когда выделены ячейки.Немедленное окно говорит мне:

?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"}

Ответы [ 2 ]

0 голосов
/ 19 февраля 2019

Альтернатива - создать функцию IsRange и перехватить любую system.InvalidCastException, которая является Type из Exception thrown, когда 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
0 голосов
/ 18 февраля 2019

Сначала проверьте ваши ссылки.

Я вижу проблему, когда я включил ссылки как на Microsoft.Office.Interop.Excel, так и Microsoft office 15.0 object library.Позже я попробовал только первый.Вопрос исчез.

Если нет проблем со ссылками, попробуйте, как сказано ниже.

Сначала получите объект активного рабочего листа.

Затем используйте объект объекта рабочего листа для проверкивыбор

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

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

End If
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...