簡體   English   中英

獲取工作表作為集合 excel vba

[英]Get worksheet as collection excel vba

我正在 excel 中構建一個基本的表單宏。 用戶通過我的表單傳遞工作簿 object 名稱,即完整文件路徑和工作表名稱。 然后宏需要打開激活工作簿,找到並激活工作表,然后將工作表上的所有數據復制到一個集合中。 該集合將通過 ByRef 或 ByVal 傳遞給另一個子。 I'm not efficient with Microsoft Excel VBA re its libraries, I work in a vb.net environment, the below code is what I would run in vb.net to get my worksheets data as a collection. 您會注意到在下面的代碼中使用了三個函數,GetWorksheet()、GetClipboardText() 和 ParseDelimSeparatedVariables()。 希望有人可以對如何重新創建此建議 Excel VBA。

Assembly References: System.Data.dll, System.Xml.dll, System.Drawing.dll, System.Windows.Forms.dll

Namespace Imports: System, System.Drawing, System.Collections.Generic, System.IO, Microsoft.VisualBasic, System.Windows.Forms, System.Data, System.Diagnostics, System.Text, System.Threading, System.Runtime.InteropServices

Dim ws as Object = GetWorksheet(handle, workbookname, worksheetname, False)

' Do we have a sheet?
sheetexists = ws IsNot Nothing
' No sheet? No entry.
If Not sheetexists Then Return

ws.Activate()
ws.UsedRange.Select()
ws.UsedRange.Copy()

Dim data As String = GetClipboardText()
                
worksheetCollection = ParseDelimSeparatedVariables(data, vbTab, Nothing, True)

下面是我現在得到的 VBA 代碼,目前出現運行時錯誤 9 subscript out of range 錯誤。

Sub getWSCol()

Dim wb As String
Dim wsName As String
Dim Arr() As Variant
Dim v As Variant
Dim colMailMerge As New Collection
        
wb = txtbxworkbook
wsName = txtbxworksheet
            
Workbooks(wb).Worksheets(wsName).Activate
        
Arr = Worksheets(wsName).UsedRange.Value
       
For Each v In Arr
    col.Add v
Next v
    
End Sub

下圖是單步執行代碼在此處輸入圖像描述

VBA缺少很多讓你的生活變得輕松的功能,所以需要自己動手。

集合不會導致所有單元格文本的單一維度列表嗎? 數組可能是更好的用例。

Dim Arr() as Variant
Arr = ws.UsedRange.value

我認為如果想要一個集合,你必須遍歷一個數組,到那時就可以輕松完成

Dim Col as new Collection
Dim v as Variant
for each v in Arr
    col.add v
next v

獲取工作表,只需在Application.Workbooks(name).Worksheets(name)對象中按名稱引用。 如果沒有,它會出錯,所以需要 function 上的內容,然后錯誤恢復錯誤,然后可以測試 function 之外是否沒有任何內容。

對於單...

Dim Wk as workbook, Ws as worksheet
On error resume next
set wk = application.worksbooks(Wkbkname)
set ws = wk.worksheets(wsname)
on error goto 0
if ws is nothing then msgbox "Doesn't exist"

Arr = ws.UsedRange.Value

暫無
暫無

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

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