Use*_*own 1 excel vba excel-vba
我正在更新基于可用性代码的容量表.特定范围内的可用性代码具有相同的容量(少数例外).每个可用性代码都列在"F"列中.相关容量将列在"I"列中.
该代码的目标是:
Row.Offset迭代一行并用数据重复到最后一个"F"单元格
Sub Capacity()
Dim ACNum As Range
Dim WB As Workbook
Dim WS As Worksheet
Set WB = ActiveWorkbook
Set WS = WB.ActiveWorksheet
Set ACNum = WS.Range("F:F")
For Each Row In ACNum.Cells
Set AC = WS.Cells(WS.Rows.Count, "F").End(xlUp).Offset(1)
If (AC = "762" Or AC = "763" Or AC = "764" Or AC = "765" Or AC = "768") Then
Row.Offset(0, 3).Value = "72"
ElseIf (AC >= "300" And AC <= "499") Then
Row.Offset(0, 3).Value = "181"
ElseIf (AC >= "500" And AC <= "599") Then
Row.Offset(0, 3).Value = "163"
ElseIf (AC >= "600" And AC <= "699") Then
Row.Offset(0, 3).Value = "124"
ElseIf (AC >= "700" And AC <= "799") And _
(AC <> "762" Or AC <> "763" Or AC <> "764" Or AC <> "765" Or AC <> "768") Then
Row.Offset(0, 3).Value = "144"
End If
Next Row
End Sub
Run Code Online (Sandbox Code Playgroud)每次执行此操作时,我都会在第13行(第一个If语句的开头)收到一个黄色突出显示的泛型错误.如果我尝试使用Excel的评估工具,它的选项是灰色的,我无法单步执行宏.
我无法确定我做错了什么.我有一段时间没有在Excel VBA工作过,所以我可能会错过一个小细节.这似乎很直截了当.
编辑:添加了"公式"方法解决方案
这应该做
Option Explicit
Sub Capacity()
Dim cell As Range
Dim noNumbers As String
Dim code As Integer
noNumbers = "-762-763-764-765-768-" '<== code exceptions
For Each cell In ActiveSheet.Columns("F").SpecialCells(xlCellTypeConstants, xlNumbers) '<= consider only numbers in "availibility code" column
With cell
If InStr(noNumbers, "-" & .value & "-") > 0 Then
code = 72
Else
Select Case .value
Case 300 To 499
code = 181
Case 500 To 599
code = 163
Case 600 To 699
code = 124
Case 700 To 799
code = 144
Case Else
code = -1
End Select
End If
.Offset(0, 3) = code
End With
Next cell
End Sub
Run Code Online (Sandbox Code Playgroud)
根据你的解释我假设"可用性代码"实际上是一个数字,因此声明并使用code类型为"integer" 的变量()来处理它然后使用Select Case语句来消除解析标准以避免重复很多人物
正如Dan Donoghue提出的那样,你可能想要使用公式方法.我想出了以下内容,使用"中位数"功能从http://chandoo.org/wp/2010/06/24/between-formula-excel/
Sub Capacity2()
With ActiveSheet.Columns("F").SpecialCells(xlCellTypeConstants, xlNumbers) '<= consider only numbers in "availibility code" column
.Offset(, 3).FormulaR1C1 = "=if(isnumber(search(""-"" & RC[-3] & ""-"",""-762-763-764-765-768-"")),72," _
& "if(RC[-3]=MEDIAN(RC[-3],300,499),181," _
& "if(RC[-3]=MEDIAN(RC[-3],500,599),163," _
& "if(RC[-3]=MEDIAN(RC[-3],600,699),124," _
& "if(RC[-3]=MEDIAN(RC[-3],700,799),144,-1" _
& ")))))"
End With
Run Code Online (Sandbox Code Playgroud)
当然,您也可以直接在excel单元格中实现,而不是运行VBA宏