用 Visual Studio 封裝 EXCEL VBA
環境
Visual Studio 2010
Excel 2007
Windows 8.1
(我的環境很舊我知道...)
開新專案
將自動產生的 Class1.vb 刪除
產生新項目
建立新檔案
更改專案設定
確定這個有打勾
加入引用
找到 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)
確認一下再存檔
貼上程式碼
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
將錯誤的提示打開
會自動加入一行 import
產生結果檔
出現錯誤訊息
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. |
將 Visual Studio 關掉,以系統管理員身分重新執行
記得切換成 Release
再產生結果檔
檢查 Release 資料夾,產生成功
將.dll 檔、.tlb 檔和 excel 檔放一起,其實主要是.tlb 檔
打開 excel 檔,新增巨集程式
按工具->設定引用項目
照圖找剛剛做好的 tlb 檔
輸入程式碼
Sub Test01()
Dim ABC As New ComExcel2
ABC.Test
End Sub
執行
成功
如果要在別的電腦執行
必須註冊 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
留言列表