[英]Passing a range of columns as a constant parameter
我正在嘗試將一系列列作為 function 的參數傳遞。
For sr = 1 To srCount
If IsEmpty(Data(sr, 4)) Then
dr = dr + 1
Data(dr, 4) = Data(sr, 1) 'instead of just the first column, a range of columns
End If
Next sr
我以為我可以定義一個范圍(“A:C”)並將其引用作為參數傳遞,但 VBA 似乎只接受(引用)長變量/常量作為 Data() function 的參數。什么這種事情的正確語法是什么?
編輯 01/26 以澄清: Data
是一個數組。 目標是根據該行中的另一個單元格為空的條件 ( If IsEmpty(Data(sr, 4))
) 復制一系列列中的一行。 例如,如果單元格 (7,4) 為空,則應將 AC 列的第 7 行復制到工作表的另一個區域 (K2:M2)。 如果 (13,4) 為空,則為第 13 行,列 AC 到 K3-M3,依此類推。
根據@Cameron 的提示,我使用 Collections 來存儲范圍。
Dim users As New Collection
Dim cell As Range
With Worksheets(2)
users.Add .Range("A:C"), "Users"
users.Add .Range("K:M"), "FinalList"
End With
For Each cell In users.Item("Users")
For sr = 1 to srCount
If IsEmpty(Data(sr, 4)) Then
dr = dr + 1
FinalList = Users
End If
Next sr
Next
盡管進行了研究,但我找不到如何為此目標操縱 Collections。 一旦我將所有必要的值存儲在 FinalList 中,我如何將它們復制到目標范圍(“K:M”)?
Option Explicit
Sub Test()
Const SRC_CRITERIA_COLUMN As Long = 4
Const DST_WORKSHEET_ID As Variant = 2 ' using the tab name is preferable!
Const DST_FIRST_CELL As String = "K2"
' The following could be calculated from the source variables.
Const DST_COLUMNS_COUNT As Long = 3
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' whatever...
Dim Data() ' ?
Dim srCount As Long ' ?
' whatever...
Dim sr As Long, dr As Long, c As Long
' Write the matching values to the top of the array
' When using a single array, the result needs to be in the top-left
' of the array. The data of interest is already left-most
' so there is no column offset.
For sr = 1 To srCount
If IsEmpty(Data(sr, SRC_CRITERIA_COLUMN)) Then
dr = dr + 1
For c = 1 To DST_COLUMNS_COUNT
Data(dr, c) = Data(sr, c)
Next c
End If
Next sr
' Reference the destination range.
Dim dws As Worksheet: Set dws = wb.Worksheets(DST_WORKSHEET_ID)
Dim dfCell As Range: Set dfCell = dws.Range(DST_FIRST_CELL)
' Note how you're using just the 'dr' number of rows
' and 'DST_COLUMNS_COUNT' number of columns.
Dim drg As Range: Set drg = dfCell.Resize(dr, DST_COLUMNS_COUNT)
' Write the result from the top-left of the array to the destination range.
drg.Value = Data
' Clear below.
drg.Resize(dws.Rows.Count - drg.Row - dr + 1).Offset(dr).ClearContents
MsgBox "Data copied.", vbInformation
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.