在excel文件及其相关列中查找特定值

时间:2016-05-11 02:20:24

标签: excel vba

我在VBA中非常新,我希望找到行的最小值并通过创建命令按钮返回其列号。 例如,连续: 3 2 2 4 5 6 7 我需要返回第2列,即使2出现两次。

我的代码目前看起来像这样:

Private Sub CommandButton1_Click()
Dim myrange As range
Dim answer As Double
Dim f As Range
Dim column1 As Integer

Set myrange = Worksheets("Solver VBA").range("C94:T94")
answer = Application.WorksheetFunction.Min(myrange)
MsgBox answer

Set f = Worksheets("Solver VBA").Cells.Find(answer).Column
MsgBox f
End Sub

我在第3行的第3行继续收到运行时错误“91”和黄色突出显示。

编辑:我按照建议尝试了这些步骤并且它有效(但是它给了我第3列而不是2,这在我的情况下也很好):

Private Sub CommandButton1_Click()

Dim myrange As range
Set myrange = Worksheets("Solver VBA").range("C94:T94")

Dim answer As Double
answer = Application.WorksheetFunction.Min(myrange)
MsgBox answer
Private Sub CommandButton1_Click()

Dim column1 As Integer
column1 = Application.Match(answer, myrange, 0) + 2
MsgBox column1

End Sub

3 个答案:

答案 0 :(得分:2)

我建议这样做(保留所有变量):

Private Sub CommandButton1_Click()

  Dim myrange As Range
  Set myrange = Worksheets("Solver VBA").Range("C94:T94")

  Dim answer As Double
  answer = Application.Min(myrange)

  Dim column1 As Integer
  column1 = Application.Match(answer, myrange, 0) + 2

  Dim f As Range
  Set f = Application.Index(myrange.EntireRow, 1, column1)

End Sub

如果你只需要范围(包含值的单元格),你也可以直接使用类似的东西:

Set f = Worksheets("Solver VBA").Range("B94").Offset(, Application.Match(Application.Min(Worksheets("Solver VBA").Range("C94:T94")), Worksheets("Solver VBA").Range("C94:T94"), 0))

或者像我的评论中那样得到列号:

column1 = Application.Match(Application.Min(Worksheets("Solver VBA").Range("C94:T94")), Worksheets("Solver VBA").Range("C94:T94"), 0) + 2

应该是自我解释。但如果你还有任何问题,请问;)

答案 1 :(得分:1)

考虑

  1. f调暗为
  2. 放弃Set
  3. 使用 .Column
  4. 保持MsgBox
  5. 使用 .Columns ,您会看到一个Range对象。使用 .Column ,您可以获得很长的效果。

答案 2 :(得分:0)

更改

Call otherpracticesub

**Exit Sub**
'Nothing more can execute here so its no longer a worry

MsgBox ("We're in the other practice sub!")