close

用 Visual Studio 封裝 EXCEL VBA

環境
Visual Studio 2010
Excel 2007
Windows 8.1
(我的環境很舊我知道...)

開新專案

0010.jpg

0020.jpg

將自動產生的 Class1.vb 刪除

0030.jpg

產生新項目

0040.jpg

建立新檔案

0050.jpg

更改專案設定

0060.jpg

確定這個有打勾

0070.jpg

加入引用

0080.jpg

找到 Excel 

注意,不同版本的 EXCEL 在 COM 裡顯示的版本號不同

EXCEL2000(Microsoft Excel 9.0 Object Library)
EXCEL2002(Microsoft Excel 10.0 Object Library)
EXCEL2003(Microsoft Excel 11.0 Object Library)
EXCEL2007(Microsoft Excel 12.0 Object Library)
EXCEL2010(Microsoft Excel 14.0 Object Library)
EXCEL2013(Microsoft Excel 15.0 Object Library)

0090.jpg

確認一下再存檔

0100.jpg

貼上程式碼

Public Sub Test()
        On Error Resume Next
        Dim VbApp As Excel.Application
        Dim VbSht As Excel.Worksheet
        VbApp = GetObject(, "Excel.Application")
        VbSht = VbApp.ActiveSheet
        VbSht.Cells(1, 1).Value = "123"
End Sub

0110.jpg

將錯誤的提示打開

0120.jpg

會自動加入一行 import

0130.jpg

產生結果檔

0140.jpg

出現錯誤訊息

Cannot register assembly "D:\VBATest\VBADLL\VBADLL\bin\Release\VBADLL.dll" - access denied. Please make sure you're running the application as administrator. Access to the registry key 'HKEY_CLASSES_ROOT\VBADLL.ComExcel' is denied.

0150.jpg

將 Visual Studio 關掉,以系統管理員身分重新執行

0160.jpg

記得切換成 Release

0180.jpg

再產生結果檔

0181.jpg

檢查 Release 資料夾,產生成功

0190.jpg

將.dll 檔、.tlb 檔和 excel 檔放一起,其實主要是.tlb 檔

0200.jpg

打開 excel 檔,新增巨集程式

0210.jpg

按工具->設定引用項目

0220.jpg

照圖找剛剛做好的 tlb 檔

0230.jpg

輸入程式碼

Sub Test01()
    Dim ABC As New ComExcel2
    ABC.Test
End Sub

0240.jpg

0250.jpg

執行

0260.jpg

成功

0270.jpg

如果要在別的電腦執行
必須註冊 COM 
但是因為我現在沒有別的電腦可以試....
所以沒有辦法測試

參考網頁
https://blog.csdn.net/chinaherolts2008/article/details/125100818
https://www.itread01.com/content/1547517442.html
https://ttlkwt912.pixnet.net/blog/post/465764786
https://zhuanlan.zhihu.com/p/81036684

arrow
arrow
    文章標籤
    Visual Studio excel vba
    全站熱搜

    kamory 發表在 痞客邦 留言(0) 人氣()