簡體   English   中英

VBA-使用.NET類庫

[英]VBA - Using .NET class library

我們有一個自定義類庫,該類庫是從頭開始構建的,可以執行適當的業務模型所需的各種功能。 我們還使用VBA自動從標准Microsoft軟件包和SolidWorks中插入一些數據。

迄今為止,我們基本上已經在VBA應用程序宏中重新編寫了代碼,但是現在正在將類庫包含到VBA引用中。 我們已經為COM互操作注冊了類庫,並確保它對COM可見。 該文件是可引用的,我們在每個Public <ClassInterface(ClassInterfaceType.AutoDual)> _上方添加了<ClassInterface(ClassInterfaceType.AutoDual)> _標記,以便智能操作。

話雖如此,現在出現了問題-當我們引用類庫時,對於該實例,我們將其Test_Object ,它將被拾取並且似乎可以正常工作。 因此,我們繼續嘗試一個小示例,以確保它正在使用公共函數並返回期望值:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim test As New Test_Object.Formatting
    Dim t As String
    t = test.extractNumber("abc12g3y45")
    Target.Value = t
End Sub

這將按預期方式工作,在選定的單元中返回12345。

但是,當我嘗試另一個類時,按照完全相同的步驟進行操作,則會收到錯誤消息( Object variable or With block variable not set )。 代碼如下:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim test As New Test_Object.SQLCalls
    Dim t As String
    t = test.SQLNumber("SELECT TOP 1 ID from testdb.dbo.TESTTABLE") 'where the string literal in the parentheses is a parameter that is passed.
    Target.Value = t
End Sub

這在t = test.SQLNumber行上失敗。 它還在該SQLCalls類中的另一個函數上失敗,該函數以SQL格式返回日期(因此,與數據庫連接無關)。

任何人都可以協助導致此錯誤的原因嗎? 我已經搜索了幾個小時無濟於事,並且願意嘗試一切以使其正常工作。

干杯。

編輯:(在.SQLNumber()方法中添加)

Function SQLNumber(query As String) As Double
    Dim tno As Double
        Try
            Using SQLConnection As SqlConnection = New SqlConnection(Connection_String_Current)
                SQLConnection.Open()
                SQLCommand = New SqlCommand(query, SQLConnection)
                tno = SQLCommand.ExecuteScalar
            End Using
        Catch ex As System.Exception
            MsgBox(ex.Message)
        End Try
    Return tno
End Function

為了進行比較, extractNumber()方法:

Function extractNumber(extstr As String) As Double
    Dim i As Integer = 1
    Dim tempstr As String
    Dim extno As String = ""
    Do Until i > Len(extstr)
        tempstr = Mid(extstr, i, 1)
        If tempstr = "0" Or tempstr = "1" Or tempstr = "2" Or tempstr = "3" Or tempstr = "4" Or tempstr = "5" Or tempstr = "6" Or tempstr = "7" Or tempstr = "8" Or tempstr = "9" Or tempstr = "." Then
            extno = extno & tempstr
        End If
        i = i + 1
    Loop
    If IsNumeric(extno) Then
        Return CDbl(extno)
    Else
        Return 0
    End If
End Function

在vba4all的幫助下,我們設法深入研究了該問題。

當我嘗試使用Dim x as new Test_Object.SQLCalls創建對象的新實例時,我完全忘記了我沒有重新輸入以下關鍵行這一事實: <ClassInterface(ClassInterfaceType.None)> _

在執行此操作之前,我將其放在對象瀏覽器中,該瀏覽器的“類”部分中同時包含ISQLCalls和SQLCalls 在此處輸入圖片說明

但是,等等,ISQLCalls不是一個類,而是一個接口!

通過在SQLCalls類中輸入<ClassInterface(ClassInterfaceType.None)> _ ,對象瀏覽器看起來會更好一些:

在此處輸入圖片說明

瞧瞧,我現在可以創建該類的新實例,並公開這些方法。

tldr:我需要顯式聲明接口,並在接口上使用<InterfaceType(ComInterfaceType.InterfaceIsDual)> ,並在類中使用<ClassInterface(ClassInterfaceType.None)>

非常感謝vba4all,他花了無私的時間來協助解決此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM