excel 将工作表单元格设置为返回另一工作簿中定义的函数的值

yzuktlbb  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(175)

我有两个文件,重要的是文件类型保持不变。首先,Stack.xlsm

只有一行数据。下面的函数取两个数据点,并将它们保存到返回的数组中。因此,单元格A5=StudentData(1),B5=StudentData(2)

Public Function StudentData(Index As Integer)
    Dim StudentID As Double
    Dim StudentScore As Double
    Dim IntA(1 To 2) As Double

    StudentID = ActiveSheet.Cells(2, 1)
    StudentScore = ActiveSheet.Cells(2, 2)
    
    IntA(1) = StudentID
    IntA(2) = StudentScore
    
    StudentData = IntA(Index)
    
End Function

第二个是Test.xlsx。我试图将这个文件保存为.xlsx,但不知何故向其中写入了数据(这应该是运行所需sub后的结果):

我想覆盖此工作表中的单元格,使A1=“ID:“& StudentData(1),B1=“Score:“&StudentData(2),即调用Stack.xlsm中定义的函数
我假设这将在Stack.xlsm中实现,如下所示:

Public Sub DataTransfer()
    Workbooks("Test.xlsx").Worksheets("Sheet1").cell(A1) = "ID:" & StudentData(1)
    Workbooks("Test.xlsx").Worksheets("Sheet1").cell(B1) = "Score:" & StudentData(2)
End Sub

语法是错误的,但我希望它表明我的意图。

7bsow1i6

7bsow1i61#

复制值

  • 当你执行Dim Student(1 To 2) As Double时(或者在你的函数Dim IntA(1 To 2) As Double中),你已经决定了你将通过索引来访问值,即Student(1)Student(2)。没有必要(可能)为此使用索引参数。
  • 如果要对行索引进行硬编码,则函数签名将为
Function StudentData(ByVal ws As Worksheet) As Double()

一个参数。

  • 如果您还要对工作表进行硬编码,则函数签名将为
Function StudentData() As Double()

没有参数。
"一个想法"

Function StudentData( _
    ByVal ws As Worksheet, _
    ByVal RowIndex As Long) _
As Double()
    
    ' 'StudentID' and 'StudentScore' are beautiful variable names,
    ' but they don't serve much of a purpose.
    Dim StudentID As Double: StudentID = ws.Cells(RowIndex, "A").Value
    Dim StudentScore As Double: StudentScore = ws.Cells(RowIndex, "B").Value
    
    Dim Student(1 To 2) As Double
    Student(1) = StudentID
    Student(2) = StudentScore
    
    StudentData = Student
    
End Function

Sub DataTransfer()
    
    Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets("Sheet1")
    Dim sRow As Long: sRow = 5
    Dim Student() As Double: Student = StudentData(sws, sRow)
    
    Dim dws As Worksheet: Set dws = Workbooks("Test.xlsx").Worksheets("Sheet1")
    Dim dRow As Long: dRow = 1
    
    dws.Cells(dRow, "A").Value = "ID:" & Student(1)
    dws.Cells(dRow, "B").Value = "Score:" & Student(2)

End Sub
  • 希望您只是在练习如何更好地理解范围、数组、函数等,因为所有这些复杂性都可以归结为以下几点:
Sub DataTransferSolo()
    Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets("Sheet1")
    Dim dws As Worksheet: Set dws = Workbooks("Test.xlsx").Worksheets("Sheet1")
    dws.Range("A1").Value = "ID:" & sws.Range("A5").Value
    dws.Range("B1").Value = "Score:" & sws.Range("B5").Value
End Sub

"终于"

  • 在最终了解您在做什么之后,它的问题是,您检索两个值(将它们从工作表写入数组),而只获得一个值作为函数的结果,这是相当低效的,因为您必须运行它两次才能获得两个值。
  • 如上面的代码所示,传递一个数组作为结果,只读取一次数据(最重要的是,只访问一次工作表),这是一种可行的方法。您可以在调用过程中有效地(快速地)从传递的数组中多次访问任何值。

相关问题