業務部門每月提交每月財務信息公司。開發一個將從多個業務部門獲取財務數據的VBA宏。
APPROACH
- 創建主簿,它整合各業務部門的信息。確保每個業務單元在主簿(「
Target_workbook
‘)代表用自己的標籤(如‘1120’,‘1130’,‘1210’,’businessUnit
」) - 從每個業務創建一個數組單元片(「
arr
‘) - 使用數組的信息來找到相應的月度財務報告(’
Source_Workbook
」,「Source_Path
‘) - 複製和財務信息粘貼到主簿(’
Target_workbook
」)和相應的業務單位的標籤(businessUnit
)
CODE
Sub getBusinessUnits()
Dim ws As Worksheet
Dim Target_Workbook As Workbook
Dim Source_Workbook As Workbook
Dim element As Variant
Dim col As New Collection
Dim Source_Path As String
Dim businessUnit As String
Dim businessName As String
'Set up collection to identify Business Unit Tabs and convert into array
For Each ws In ThisWorkbook.Worksheets
If IsNumeric(ws.Name) Then
col.Add ws.Name
Dim arr As Variant
End If
Next
arr = toArray(col) 'Collection converted into Array
'Loop through worksheets in array, open relative workbook, and pull in relevant data
For i = LBound(arr, 1) To UBound(arr, 1)
'assign business unit information to variables.
'Define workbook where we will paste copied information (target_workbook)
businessUnit = ThisWorkbook.Sheets(arr(i)).Activate
Set Target_Workbooks = ThisWorkbook.Sheets(arr(i))
businessName = ActiveSheet.Cells(2, 2)
'Open up the corresponding business unit's financial report, copy data
Source_Path = ThisWorkbook.Path & "\Business Unit Monthly Reporting Template_" & businessName & ".xlsx"
Set Source_Workbook = Workbooks.Open(Source_Path)
Source_Workbook.Sheets("Auth Expense Data Entry").Range("A1:H150").Copy
'Paste copied information from Source_Workbook into Target_workbook
Target_Workbook.Sheets(arr(i)).Range("A5").PasteSpecial Paste:=xlPasteValues '!!!ERROR: "Object Variable or With Block variable not set" !!!!
'Clear cache, close source_workbook
Application.CutCopyMode = False
Source_Workbook.Close (False)
End
Next
End Sub
'Function to convert collection into array
Function toArray(col As Collection)
Dim arr() As Variant
ReDim arr(1 To col.Count) As Variant
For i = 1 To col.Count
arr(i) = col(i)
Next
toArray = arr
End Function
問題
- 錯誤@行:
Target_Workbook.Sheets(arr(i)).Range("A5").PasteSpecial Paste:=xlPasteValues
, 「對象變量或With塊變量未設置」。爲什麼會這樣? 是否因爲arr(i)是變體/字符串? - 其他代碼改進建議?
數百個具有相同錯誤消息的現有帖子中沒有一個幫助您?我知道我已經多次看到了這個確切的問題(這裏提供了同樣的解決方案)。請在這裏發佈一個新問題之前做一些基礎研究,其中包括閱讀大量搜索結果,這些結果將在您收錄的** exact **錯誤消息中搜索。在相關**列表=== >>>中已經提到了10個,當您在撰寫帖子時,該網站建議將其作爲潛在重複項目,甚至不需要搜索。 –