VBa и Excel: суммируйте выделенные значения ячеек из определенного номера элемента, а затем вычтите значение ячеек из другой таблицы и отобразите в следующем столбце. - PullRequest
2 голосов
/ 28 сентября 2019

Я изучаю Excel и VBa, и у меня возникают следующие проблемы, я хотел бы суммировать выделенные кол-во ячеек из правого столбца (G) (где номер элемента и дата начала равны из левой таблицы для того же номера элемента), а затемвычтите QTY из левого столбца (B) для того же номера элемента и, наконец, отобразите эти результаты в столбце (K) рядом с выделенным номером элемента.Таблицы являются динамическими.Надеюсь, это понятно, что я хочу сделать. Я пытаюсь суммировать Qty в столбце G для выделенного элемента, а затем вычесть Qty в первом столбце для того же номера элемента и отобразить в столбце (K), но не работает.

Tables

Sub check()
Dim lastData, lastData1 As Variant
Dim item1, item2 As Variant
Dim endD1, startD1, endD2, startD2 As Variant
Dim i As Integer
Dim ii As Integer
Dim countQ As String

'This will find "." in the date and replace it with "/" which is neccessary before to find a macht
Cells.Replace What:=".", Replacement:="/", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

lastData = Sheet7.Cells(Sheet7.Rows.count, 1).End(xlUp).row
lastData1 = Sheet7.Cells(Sheet7.Rows.count, 6).End(xlUp).row

'Loop through  tables
For i = 3 To lastData
  item1 = Cells(i, 1).value
  startD1 = Day(Cells(i, 3).value) & Month(Cells(i, 3).value) & Year(Cells(i, 3).value)
  endD1 = Day(Cells(i, 4).value) & Month(Cells(i, 4).value) & Year(Cells(i, 4).value)
   For ii = 3 To lastData1
      item2 = Cells(ii, 6).value
      startD2 = Day(Cells(ii, 8).value) & Month(Cells(ii, 8).value) & Year(Cells(ii, 8).value)
      endD2 = Day(Cells(ii, 9).value) & Month(Cells(ii, 9).value) & Year(Cells(ii, 9).value)
      If item1 = item2 And startD1 = startD2 And endD1 = endD2 Then
      highlight (ii)

      End If
Next ii
'Compare Data from first table (column A,C) and from second table (column F,H)and then substract to column
countQ = 0
If item2 = Cells(J, 6).Interior.Color = 65535 Then
    If startD2 = Cells(J, 6).Interior.Color = 65535 Then
       If item1 = item2 And startD1 = startD2 Then
          countQ = countQ + Cells(i, 7).value
          Cells(i, 11).value = countQ - Cells(i, 1).value


       End If
     End If
End If
Next i
End Sub

Function highlight(ByVal x As Integer)
    Range("F" & x & ":J" & x).Select
    Application.CutCopyMode = False
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Function

1 Ответ

1 голос
/ 29 сентября 2019

мне кажется, ваш код должен быть таким (пояснения в комментариях):

Option Explicit ' <-- use this to force variables explicit dimensioning

Sub check()
' all variables must be dimensioned with its own type: unspecified types default to Variant
    Dim lastData As Variant, lastData1 As Variant 
    Dim item1 As Variant, item2 As Variant
    Dim endD1 As Variant, startD1 As Variant, endD2 As Variant, startD2 As Variant
    Dim i As Long
    Dim ii As Long
    Dim countQ As Long ' <-- you need it a numeric variable!

    'This will find "." in the date and replace it with "/" which is neccessary before to find a macht
    Cells.Replace What:=".", Replacement:="/", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    lastData = Sheet7.Cells(Sheet7.Rows.Count, 1).End(xlUp).Row
    lastData1 = Sheet7.Cells(Sheet7.Rows.Count, 6).End(xlUp).Row

    'Loop through  tables
    For i = 3 To lastData
        item1 = Cells(i, 1).Value
        startD1 = Day(Cells(i, 3).Value) & Month(Cells(i, 3).Value) & Year(Cells(i, 3).Value)
'        endD1 = Day(Cells(i, 4).Value) & Month(Cells(i, 4).Value) & Year(Cells(i, 4).Value) ' as per your wording, you don't seem to need endDate comparison

        countQ = 0 ' reset the second table Qty counter
        For ii = 3 To lastData1
            item2 = Cells(ii, 6).Value
            startD2 = Day(Cells(ii, 8).Value) & Month(Cells(ii, 8).Value) & Year(Cells(ii, 8).Value)
'            endD2 = Day(Cells(ii, 9).Value) & Month(Cells(ii, 9).Value) & Year(Cells(ii, 9).Value) ' as per your wording, you don't seem to need endDate comparison
            If item1 = item2 And startD1 = startD2 Then ' And endD1 = endD2 Then ' as per your wording, you don't seem to need endDate comparison
                highlight ii
                countQ = countQ + Cells(ii, 7).Value ' update the second table qty counter
                Cells(ii, 11).Value = Cells(i, 2).Value - countQ ' subtract the current second table qty counter form first table qty and place it in coumn K of current second table row
            End If
        Next    
    Next
End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...