excel 如何修改VBA函数以在不打开另一个工作簿的情况下访问该工作簿中的数据?

c9x0cxw0  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(225)

从其他工作簿VBA函数访问数据。

你好,我有一个VBA函数,它可以遍历打开的工作簿的工作表,并添加单元格A1中的值。
我的问题是我只能指定打开的工作簿的名称。我想让它这样我就不必打开工作簿,但可以使用基于路径的值。

Function test(wbName As String, ByVal wsName As String, ByVal wsName2 As String) As Long
    start = Workbooks(wbName).Worksheets(wsName).Index
    end = Workbooks(wbName).Worksheets(wsName2).Index
    If start <= end Then
        For i = start To end
            test = Workbooks(wbName).Worksheets(i).Range("A1").Value + test
        Next i
    ElseIf start > end Then
        MsgBox ("The start date cannot be later than the end date.!")
    End If
End Function

我希望你能理解我的问题,不幸的是英语不是我的母语。提前感谢您的帮助!

gojuced7

gojuced71#

求和单元格

Option Explicit

Function SumOfA1s( _
    ByVal WorkbookPath As String, _
    ByVal FirstWorksheetName As String, _
    ByVal LastWorksheetName As String) _
As Double
    Const PROC_TITLE As String = "Sum of A1s"
    On Error GoTo ClearError
    
    Dim wb As Workbook: Set wb = Workbooks.Open(WorkbookPath)
    
    Dim First As Long: First = wb.Worksheets(FirstWorksheetName).Index
    Dim Last As Long: Last = wb.Worksheets(LastWorksheetName).Index
    
    If First > Last Then
        MsgBox "The start date cannot be later than the end date!", _
            vbExclamation, PROC_TITLE
        Goto ProcExit
    End If
    
    Dim Value, i As Long, Result As Double
    
    For i = First To Last
        Value = wb.Worksheets(i).Range("A1").Value
        If IsNumeric(Value) Then
            Result = Result + Value
        End If
    Next i
    
    SumOfA1s = Result

ProcExit:
    On Error Resume Next
        If Not wb Is Nothing Then
            wb.Close SaveChanges:=False
        End If
    On Error GoTo 0
    Exit Function
ClearError:
    MsgBox "Run-time error '" & Err.Number & "':" _
        & vbLf & vbLf & Err.Description, vbCritical, PROC_TITLE
    Resume ProcExit
End Function

相关问题