2015-10-17 6 views
0

Позвольте мне начать с того, что я очень новичок в работе с excel и VBA, но имею некоторый опыт работы с C++.Обновление листа excel с информацией из другой книги

Ситуация:

Я пытаюсь обновить один лист с данными, полученными в другой книге. Исходный файл организован таким образом, что каждому новому рабочему биту присваивается столбец. По мере поступления большего количества билетов создается больше столбцов, и вся информация об этом билете отображается вертикально.

В основном то, что я пытаюсь сделать, это сохранить второй файл обновляется с теми же номерами билетов, как первый, но с разным форматированием:

Basic example of the two sheets

Вот что я до сих пор, хотя очень грубо для основной идеи о том, что я хотел бы код, чтобы сделать:

Sub Update_Click() //Button to update destination file 

Workbooks.open("C:\Documents\mysourcefile.xlsm") 
dim i,j as integer 
i=4 //starting column of source file where first ticket is stored 
j=2 //starting column of destination file where first ticket is stored 

while worksheets("mysourcesheet").Value(i,2)<>0 //all work has customer, but 
               //may not have a ticket 
               //number 

if Worksheets("mysourcesheet").value(i,1) = 0 Then 

i=i+1   //some columns in the source are blank due to canceled orders 
       //this is to go to the next column 

else 
if Worksheets("mysourcesheet").value(i,1)=Worksheets("mydestsheet").value(j,1) 
then 
i=i+1 
j-j+2  //go onto the next if already updated 
      //J+2 to account for formatting of the cells 

Else 
Worksheets("mysourcesheet").value(i,1)=Worksheets("mydestsheet").value(j,1) 
Worksheets("mysourcesheet").value(i,2)=Worksheets("mydestsheet").value(j,2) 
Worksheets("mysourcesheet").value(i,3)=Worksheets("mydestsheet").value(j,4) 
Worksheets("mysourcesheet").value(i,4)=Worksheets("mydestsheet").value(j,5) 

//copy the data 

i=i+1 
j=j+2 

end if 
end if 
end sub 

Я понимаю, что это, вероятно, пронизана ошибок/фундаментальных ошибок, но если кто-нибудь может протянуть руку, что было бы здорово!

ответ

1

Это скопирует новые билеты, если клиент не является пустым, с 1 столбца в источнике в 2 колонки

Private Sub Update_Click() 
    Dim wb As Workbook, ur1 As Range, ur2 As Range, i As Long 
    Dim fr1 As Long, fr2 As Long, lr1 As Long, lr2 As Long, lc1 As Long, lc2 As Long 

    Application.ScreenUpdating = False 

    Set wb = Workbooks.Open("E:\mysourcefile.xlsm") 
    Set ur1 = Me.UsedRange 
    Set ur2 = wb.Worksheets("mysourcesheet").UsedRange 

    fr1 = ur1.Row: lr1 = fr1 + (ur1.Rows.Count - 1) - 1 
    fr2 = ur2.Row: lr2 = fr2 + (ur2.Rows.Count - 1) - 1 
    lc1 = ur1.Column + ur1.Columns.Count - 2: lc2 = ur2.Column + ur2.Columns.Count - 1 

    If Len(ur2.Cells(fr1 + 1, lc2)) > 0 Then      'customer not empty 
     If ur1.Cells(fr1 + 1, lc1) <> ur2.Cells(fr1 + 1, lc2) Then 'if last cutomer differ 
      With ur1 
       .Cells(fr1 + 0, lc1 + 2) = ur2.Cells(fr2 + 0, lc2) 
       .Cells(fr1 + 1, lc1 + 2) = ur2.Cells(fr2 + 1, lc2) 
       .Range(.Cells(fr1 + 0, lc1 + 2), .Cells(fr1 + 0, lc1 + 3)).MergeCells = True 
       .Range(.Cells(fr1 + 1, lc1 + 2), .Cells(fr1 + 1, lc1 + 3)).MergeCells = True 
       .Cells(fr1 + 2, lc1 + 2) = "Target" 
       .Cells(fr1 + 2, lc1 + 3) = "Actual" 
       .Cells(fr1 + 2, lc1 + 2).ColumnWidth = .Cells(fr1 + 2, lc1).ColumnWidth 
       .Cells(fr1 + 2, lc1 + 3).ColumnWidth = .Cells(fr1 + 2, lc1).ColumnWidth 
    .Range(.Cells(fr1, lc1 + 2), .Cells(fr1 + 2, lc1 + 3)).HorizontalAlignment = xlCenter 
    .Range(.Cells(fr1, lc1 + 2), .Cells(lr1 + 1, lc1 + 3)).Borders.Weight = xlThin 
       For i = fr1 + 3 To lr1 + 1 
        .Cells(i, lc1 + 2) = Now 'Target date 
        .Cells(i, lc1 + 3) = ur2.Cells(i - 1, lc2) 
       Next 
      End With 
     End If 
    End If 
    wb.Close False 
    Application.ScreenUpdating = True 
End Sub 

enter image description here

+0

Спасибо так много! Я постараюсь это наверняка! –