【问题标题】:Determine Slope and Intercept using Dynamic Arrays VBA使用动态数组 VBA 确定斜率和截距
【发布时间】:2016-10-20 22:59:26
【问题描述】:

我已经有一段时间没有在 Excel VBA 中使用数组了,所以请原谅我......

我正在尝试定义一个基于动态数组的连续匹配单元格,这些单元格在循环中确定。我确定我的语法对于定义数组是错误的,我只是不确定如何。困难在于我的数组在 1 列中包含大约 6 个连续行,以及不同列中的另一个单元格。有什么想法吗?

Sub calib_range()
Dim instrument As Variant
Dim calibrator As Variant
Dim lastrow As Integer

lastrow = ThisWorkbook.ActiveSheet.Range("b2").SpecialCells(xlCellTypeLastCell).Row

For i = 4 To lastrow

If Cells(i, 4) Like "MPC*" Then
'enter loop to determine length of MPC* array
  For x = i + 1 To lastrow
    If Cells(x, 4) = Cells(x - 1, 4) Then
      Else
      x = x - 1
      Exit For
    End If
  Next x

  instrument = Array(Cells(i, 17), Range(Cells(i, 14), Cells(x, 14)))
  calibrator = Array(0, Range(Cells(i, 12), Cells(x, 12)))
  Slope = Application.WorksheetFunction.Slope(instrument, calibrator)
  Intercept = Application.WorksheetFunction.Intercept(instrument, calibrator)
  Cells(i, 22) = Slope
  Cells(i, 23) = Intercept
End If
Next i

End Sub

【问题讨论】:

  • 您有Cells(x, 4) = Cells(x - 1, 4) Then,它直接转到Else - 您是否缺少代码?为什么If 语句要这样写?
  • @BruceWayne 可能是两个单元格中的值相似,因此不会转到 else。
  • @Vityata - 当然 - 只是好奇为什么不像 If Cells() <> Cells Then // x = x-1 // Exit For 那样设置它。 (对不起,凯尔的切线问题,我认为这不是问题的一部分,只是我注意到的。)
  • 我想是一样的不同,就像我写这篇文章时的想法一样;)

标签: arrays vba excel


【解决方案1】:

你的问题在这里:

  calibrator = Array(0, Range(Cells(i, 12), Cells(x, 12)))

你不能这样做,因为 VBA 认为在你的数组中你会得到一个 0 和一个范围。因此,您的数组由两种不同类型的值组成。这不是你需要的。

阅读here 更多关于如何初始化数组的内容,这很好解释。

编辑: 同样在上一行中,您只需创建一个范围数组。对你有用的可能是这样的:

Public Sub CheckArray()

    Dim my_array()   As Double

    ReDim my_array(6)
    my_array(0) = Cells(1, 17)
    my_array(1) = Cells(2, 17)
    my_array(2) = Cells(3, 17)
    my_array(3) = Cells(4, 17)
    my_array(4) = Cells(5, 17)
    my_array(5) = Cells(6, 17)
    my_array(6) = Cells(7, 17)


End Sub

【讨论】:

  • calibrator = Array(0, Range(Cells(i, 12).Value, Cells(x, 12).Value)) 怎么样?
  • 这会给出一个结果,但 OP 正试图将整个范围(包含多个单元格)+ 一个零放入一个数组中。
猜你喜欢
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
相关资源
最近更新 更多