有没有一种方法来表达具有一定数量范围的变量以满足vba中的循环条件

时间:2020-01-30 12:12:21

标签: excel vba

有没有一种方法可以将变量f表示为数字范围,例如在Excel vba中f = 4到9?因为我的目的是创建一个条件,以便对于i = 1到lastColumn,如果i落在4到9的范围内,这样它将扫描从i到lastcolumn的值并接受标头(电压,功率和时间)位于单元格(1,4)到单元格(1,9)之内,此后将调用专用子电压powertime,在此位置,它会在第一次检测到其标题时通过使用电压,功率和时间列来创建多个数据透视表行。如果还有其他方式表达我的意图,我也将不胜感激。

enter image description here

 Dim sh as Worksheet

Dim LastColumn as integer

Dim f as integer

f=4 to 9 '------>How to express f as a range of number?

For i = 1 to LastColumn

if i = f Then

if sht.Cells(1,f).Value = "Voltage" And sht.Cells(1,f).Value= "Power" and sht.Cells(1,f).Value= "Time" Then

Call voltagepowertime

4 个答案:

答案 0 :(得分:1)

Like Daghan建议您可以使用循环中的If条件测试该数字是否在4到9之间,从而轻松实现所需的目标。

您的提示看起来像这样:

Dim sh as Worksheet
Dim LastColumn as integer

For i = 1 to LastColumn

  'You can easily change these numbers to fit whatever range you want
  if i >= 4 And i =< 9 Then

     if sht.Cells(1,i).Value = "Voltage" And sht.Cells(1,i).Value= "Power" and sht.Cells(1,i).Value= "Time" Then

        Call voltagepowertime

     End if

  End if
Next

答案 1 :(得分:1)

Sub testExtraction()
   Dim sh As Worksheet, i As Long
   Set sh = ActiveSheet ' use here your sheet

   For i = 4 To 9
    If sh.Cells(1, i).Value = "Voltage" Or _
          sh.Cells(1, i).Value = "Power" Or _
          sh.Cells(1, i).Value = "Time" Then
         '"extract" your column. I did not understand what this extraction means...
         sh.Cells(1, i).EntireColumn.Select: Stop
    End If
   Next i
End Sub

我不知道您所说的“提取”是什么意思。现在,选择具有正确标题的列后,代码将停止。

答案 2 :(得分:1)

这应该回答您的第二个问题/方法...

Sub testMatch()
Dim sh As Worksheet, rng As Range, voltPos As Long
 Set sh = ActiveSheet ' use please your sheet here
 Set rng = sh.Range("A1:I1")
 voltPos = IsMatch(rng, "Voltage")
 If voltPos <> 0 Then
    sh.Cells(1, voltPos).EntireColumn.Select
    'Call voltagepowertime 'You must know what this sub must do...
 Else
    MsgBox "Your string could not be found in the range..."
 End If
End Sub
Private Function IsMatch(rng As Range, strS As String) As Long
    On Error Resume Next
    IsMatch = WorksheetFunction.Match(strS, rng)
    If Err.Number <> 0 Then
        Err.Clear: On Error GoTo 0
        IsMatch = 0
    End If
    On Error GoTo 0
End Function

您可以类似地将其用于其余的字符串...

答案 3 :(得分:0)

如果存在更大范围的数字,可能不是最佳解决方案,但是您可以使用select case

select case i
    case 4,5,6,7,8,9
        'do something
    case else
        'do something else
end select