2016-04-15 68 views
0

我创建了一个组合框,它具有下面看到的不同情况。目前的公式的工作原理除了我想添加一个额外的列,复制给列C相同的值,并且希望将其添加到列R将组合框的值添加到多列

Ex。组合框 选择当前月份 我想根据搜索到的部分向列C和列R添加500个单位。

Private Sub cmdAdd_Click() 

Dim irow As Long 
Dim lastRow As Long 
Dim iCol As String 
Dim C As Range 
Dim ws As Worksheet 
Dim value As Long 
Dim NewPart As Boolean 
Set ws = Worksheets("Summary") 

Set C = ws.Range("A7:A1048576").Find(What:=Me.PartTextBox.value, SearchOrder:=xlRows, _ 
     SearchDirection:=xlPrevious, LookIn:=xlValues, LookAt:=xlWhole) 
If C Is Nothing Then 
'find first empty row in database 
    lastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count 
    irow = lastRow + 1 
    NewPart = True 
Else 
'find row where the part is 
    irow = ws.Cells.Find(What:=Me.PartTextBox.value, SearchOrder:=xlRows, _ 
     SearchDirection:=xlPrevious, LookIn:=xlValues).Row 
    NewPart = False 
End If 
'check for a part number 
If Trim(Me.PartTextBox.value) = "" Then 
    Me.PartTextBox.SetFocus 
    MsgBox "Please Enter A Part Number" 
    Exit Sub 
End If 

If Trim(Me.MonthComboBox.value) = "" Then 
    Me.MonthComboBox.SetFocus 
    MsgBox "Please Enter A Month" 
    Exit Sub 
End If 

If Trim(Me.AddTextBox.value) = "" Then 
    Me.AddTextBox.SetFocus 
    MsgBox "Please Enter A Value To Add Or Substract" 
    Exit Sub 
End If 



Select Case MonthComboBox.value 

    Case "Current Month" 

     iCol = "C" And "R" 

    Case "Current Month +1" 

     iCol = "N" 

    Case "Current Month +2" 

     iCol = "O" 

    Case "Current Month +3" 

     iCol = "P" 

    Case "Current Month +4" 

     iCol = "Q" 

End Select 
value = Cells(irow, iCol).value 
With ws 


    .Cells(irow, iCol).value = value + CLng(Me.AddTextBox.value) 


End With 

If NewPart = True Then 
    ws.Cells(irow, "A").value = Me.PartTextBox.value 
End If 


If NewPart = True Then 
ws.Cells(irow, "C").value = Me.AddTextBox.value 
End If 

回答

1

我可能会推荐使用数组来存储列。

Sub t() 
Dim iCol() 
Dim testStr$, myValue$ 
Dim iRow& 
Dim ws As Worksheet 
testStr = "Current Month" 

Select Case testStr 
    Case "Current Month" 
     iCol() = Array("C", "R") 
    Case "Current Month +1" 
     iCol() = Array("N") 
    End Select 

Dim i& 
For i = LBound(iCol) To UBound(iCol) 
    myValue = Cells(iRow, iCol(i)).value ' WHAT SHEET IS THIS ON?? 
    With ws 
     .Cells(iRow, iCol(i)).value = myValue + CLng(Me.AddTextbox.value) 
    End With 
Next i 

End Sub 

您可以根据需要添加到Case。请注意,在完成对列的处理后,您需要打包Next i,以便能够看到是否有第二个可以运行。

此外,由于您没有包含所有代码,因此您可能需要调整范围。 (请注意,myValue没有指定Cells()使用的工作表)。

+0

我已附上完整代码 – Luis

+0

@Luis - 我会更新您的代码以包含数组,如我的示例中所示。只需在'End With'之后添加'Next i',结束'With ws'语句。或者,在你的'If NewPart'部分之后,如果每列都会影响这个部分。那有意义吗? – BruceWayne