2016-06-07 89 views
2

我试过了,我真的试过了!我有两张“拖欠”和“趋势”。下面是一个用于保存单词的图像: Intended tablesExcel VBA匹配还是查找?

这个想法是让脚本循环通过工作表趋势的A列中的(现有)记录,在工作表拖欠的A列中找到匹配项。然后使用该匹配,将数字栏(拖欠表)中的相应金额过帐到趋势图背面插入列中的相应单元格(通过移动现有记录1xToRight。

我试图学习VBA,因为我我曾经使用过MATCH,发现我可以做所有事情,除了将相应的价值从拖欠款转移到趋势之外

在这个阶段之后还有其他的事情要做,但我不想问对于完整的脚本,否则我什么都不会学习!

回答

0

下面是我最近使用过的类似代码的一个小片段 不是你的问题最优化的代码,但它应该可以帮助你“看”解决方案。

Dim rngStr As String 'range declaration 
Dim currentRowIndex As Integer 'used to store the rowindex of certain searchvalues 
Dim searchStr As String 'word to search 
Dim ws As Worksheet 

'Set searchcolumn = A 
rngStr = "A:A" 
searchstring = "Cellvalue of cell in loop" 
currentRowIndex = SearchInRange(ws, rngStr, searchStr) 

If currentRowIndex <> 0 Then 
    'searchstr was found 
    Worksheets("TrendsSheet").Cells(rowIndex, ColIndex).value = Worksheets("ArrearsSheet").Cells(currentRowIndex, ColIndexOfValueYouWant).value 
End If 



Private Function SearchInRange(ws As Worksheet, rng As String, searchstring As String) As Integer 
    'return the rowindex of the first found value in a specific range 
    With ws.Range(rng) 
     Set c = .Find(searchstring, LookIn:=xlValues) 
     If Not c Is Nothing Then 
      SearchInRange = c 'searchstring found 
     Else 
      SearchInRange = 0 'searchString not found 
     End If 
    End With 
End Function 
0

从我明白我已经取得了一些代码,做你所要求的

Sub Transfer() 
Dim Wks1 As Excel.Worksheet 
Dim Wks2 As Excel.Worksheet 
Dim copyCell As Long 
Dim pasteCell As Long 
Dim RowMatched As Long 
Dim SearchItem As Double 
Dim NumberOfEntries As Long 
Dim RowMoved As Boolean 
Set Wks1 = Worksheets("Sheet1") '<== One worksheet 
Set Wks2 = Worksheets("Sheet2") '<== Another worksheet 
NumberOfEntries = Application.WorksheetFunction.CountA(Wks2.Range("A:A")) '<=== Finds the number of entries 
RowMoved = False '<===== Checks if row has been inserted 
For x = 2 To NumberOfEntries '<==== For all your entries 
SearchItem = Wks2.Cells(x, 1) '<=== What it is looking for 
On Error Resume Next 
    RowMatched = Application.WorksheetFunction.Match(SearchItem, Wks1.Range("A:A"), 0) '<== Match Items 
On Error GoTo 0 
If RowMatched <> 0 Then '<=== If found 
    If RowMoved = False Then '<== If no column has been added yet 
     Wks2.Range("E:E").EntireColumn.Insert '<=== Add new row in column E 
    End If 
    RowMoved = True '<=== Set row moved to true to indicate inserted column 
    Wks2.Cells(x, 5) = Wks1.Cells(RowMatched, 5) '<==== Copy Cell values 
End If 
Next x 



End Sub 

名称什么都你叫他们,并把这个在一个新的模块工作表。如果需要,您也可以使用列号。让我知道如果你需要任何东西:)

+0

绝对精湛的GBSingh ...谢谢你!我稍微调整了一下,以便不用输入一个完整的列,而是将每个匹配的单元格向右滑动,并输入新的拖欠数字。这是需要的,因为我将尝试先写下自己的下一个阶段。干杯! –

+0

不用担心。我很高兴我能提供帮助。如果这有帮助,你可以将答案标记为已解决,以便它可以帮助其他人,然后他们知道它的作用:) – GBSingh