【问题标题】:VBA Excel - Passing Array is not updating the referenceVBA Excel - 传递数组不更新引用
【发布时间】:2015-08-20 02:26:16
【问题描述】:

我正在使用一个函数,该函数将读取一个电子表格中的一系列单元格并将其写入另一个电子表格。

为此,我从源电子表格和目标电子表格中读取所有单元格,然后写入一个数组以比较目标电子表格中是否已经存在该值

这里的重点是我可以将值保存在数组中,但我的函数返回一个空数组。以下是我的代码 sn-p。

Private Sub UpdateBacklog_Click()
    Dim ArrSource() As String
    Dim ArrTarget() As String
    sourceRead Wks, ArrSource
    targetRead Cwks, ArrTarget
End Sub

Function targetRead(targetWks, arrayT() As String)
    .
    .
    rowCount = targetWks.Cells(Rows.Count, C_TRG_ID_COL).End(xlUp).Row
    currentRow = C_TRG_ROW
    id = 1

    ReDim arrayT(1, 1)
    If currentRow <= rowCount Then
        For currentRow = currentRow To rowCount
            ReDim arrayT(id, 1)
            arrayT(id, 1) = targetWks.Cells(currentRow, C_TRG_ID_COL).Value
            id = id + 1
            DoEvents
        Next
    End If
End Function

Function sourceRead(sourceWks, arrayS() As String)
    .
    .
    rowCount = sourceWks.Cells(Rows.Count, C_SRC_ID_COL).End(xlUp).Row
    currentRow = C_SRC_ROW
    id = 1

    If currentRow <= rowCount Then
        For currentRow = currentRow To rowCount
            sourceStatus = sourceWks.Cells(currentRow, C_SRC_STS_COL).Value
            ReDim arrayS(id, 1 To 4)
            arrayS(id, 1) = sourceWks.Cells(currentRow, C_SRC_ID_COL).Value
            arrayS(id, 2) = sourceWks.Cells(currentRow, C_SRC_DSC_COL).Value
            arrayS(id, 3) = sourceWks.Cells(currentRow, C_SRC_PRC_COL).Value
            arrayS(id, 4) = sourceStatus
            id = id + 1
            DoEvents
        Next
    End If
End Function

【问题讨论】:

  • 您是否考虑过使用具有 Dictionary Exists method 的字典对象?

标签: arrays excel vba parameters


【解决方案1】:

尝试从函数中返回数组。

Private Sub UpdateBacklog_Click()
    Dim ArrSource() As String
    Dim ArrTarget() As String
    ArrSource = sourceRead(Wks, ArrSource)
    ArrTarget = targetRead(Cwks, ArrTarget)
End Sub

Function targetRead(targetWks, arrayT() As String)
    ' lots of stuff here
    targetRead = arrayT
End Function

Function sourceRead(sourceWks, arrayS() As String)
    ' lots of stuff here
    sourceRead = arrayS
End Function

您将函数视为 subs 会更改传递给它们的 byRef 参数。函数旨在返回一个值,因此将更改后的数组重新分配给它们自己。出于所有意图和目的,这与用逗号替换字符串中的句点没有什么不同,

tmp = replace(tmp, chr(46), chr(44))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2013-08-13
    • 2019-01-27
    • 2015-06-10
    • 1970-01-01
    • 2013-08-09
    相关资源
    最近更新 更多