为VBA代码添加其他逻辑以获得其他功能

时间:2014-03-09 10:04:16

标签: vba excel-vba excel

需要在代码中添加一些额外的逻辑,以便为我做更多的事情。

所以这是:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long
Dim rng As Range
If Target.Address = Home.Range("_newCustomer").Address Then
  Set rng = Sheets("Customers").Range(IIf(Range("_newCustomer") = "Company", "Company", "Customer_Name"))
  On Error Resume Next
  i = WorksheetFunction.Match(Range("_newCustomer"), rng, 0)
  On Error GoTo 0
  Application.EnableEvents = False
  Home.Range("_paymentDue").Value = IIf(i = 0, "", Sheets("Customers").Range("Customers").Cells(i, 12))
  Home.Range("_invoiceDueDate").Value = IIf(Home.Range("_invoiceDate").Value = 0, "", Home.Range("_paymentTermsDay").Value + Home.Range("_invoiceDate").Value)
  Application.EnableEvents = True
End If
End Sub

到目前为止它工作正常,但我还需要的是当我更改范围_invoiceDate中的值时,范围_invoiceDueDate应该反映更改,例如,如果我要删除_invoiceDate _invoiceDueDate _paymentDue的所有内容都应相应地执行。另外,如果我要更改_invoiceDueDate范围内的任何内容,这是一个下拉列表,此更改还必须更改Home.Range("_invoiceDueDate").Value = IIf(Home.Range("_invoiceDate").Value = 0, "", Home.Range("_paymentTermsDay").Value + Home.Range("_invoiceDate").Value)的值,因为它显示在{{1}}上方的代码中。 / p>

请帮忙

1 个答案:

答案 0 :(得分:1)

试试这个:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False

    Dim i As Long
    Dim rng As Range
    If Target.Address = Range("_newCustomer").Address Then
      Set rng = Sheets("Customers").Range(IIf(Range("_newCustomer") = "Company", "Company", "Customer_Name"))
      On Error Resume Next
      i = WorksheetFunction.Match(Range("_newCustomer"), rng, 0)
      On Error GoTo 0
      Range("_paymentDue").Value = IIf(i = 0, "", Sheets("Customers").Range("Customers").Cells(i, 12))
    End If

    If Not Intersect(Target, Union(Range("_newCustomer"), Range("_invoiceDate"), Range("_paymentDue"))) Is Nothing Then
          Range("_invoiceDueDate").Value = IIf(CStr(Range("_invoiceDate").Value) = "", "", IIf(CStr(Range("_paymentTermsDay").Value) = "", 0, Range("_paymentTermsDay").Value) + Range("_invoiceDate").Value)
    End If

    Application.EnableEvents = True
End Sub