将组合框中的值添加到多个列中

时间:2016-04-15 16:04:45

标签: excel excel-vba combobox vba

我创建了一个组合框,下面有不同的情况。当前公式有效,除了我想添加一个额外的列,该列复制给予列C的相同值并希望将其添加到列R中。

实施例。组合框 选择当月 我想根据搜索到的部分向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 个答案:

答案 0 :(得分: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()指定工作表。