Excel宏,如果单元格具有值,则将单元格复制到某个位置

时间:2015-03-01 08:56:22

标签: excel vba copy

我正在寻找excel Macros的一些帮助,例如。如果在Desc中找到与Bill / car / rent / tax匹配的值,则将Cost值复制到正确的列。

Cost    Desc        Bill    Car Rent    Tax

155     Bill                    
165     Rent                    
195     tax                 
Cost    Desc        Bill  Car   Rent    Tax

155     Bill        155         
165     Rent              165       
195     tax                     195

可以这样做吗? 提前致谢。我试过并且可以选择值,但不知道如何粘贴它等,对vba宏不是很好。

感谢您的回复。抱歉,我仍然感到困惑只是学习东西atm。这就是我得到的可能不是正确的方法。



Sub Test()
For Each Cell In Sheets(1).Range("B:B")
    If Cell.Value = "Bill" Then
        matchRow = Cell.Row
        Rows(matchRow - 1).Select
        Selection.Copy

       
    End If
Next
End Sub




2 个答案:

答案 0 :(得分:0)

看来你有一个sub来查找值(vlookup / match)但不知道如何将这个值放到工作表中?

如果单元格有值,则检查或执行某些操作 您可以通过检查单元格是否为空来执行此操作,如果为true则执行此操作,如果为false则执行此操作。

With worksheets("name")
if .range("A1") = empty then
do something (for example, Application.WorksheetFunction.VLookup() )
else
do something else ("exit sub" if you want it to do nothing)
end with

存储值并将其放置在活动工作表中

dim i (this doesn't have to be "i") as string

i = your function
worksheets("name").range("A2").value = i

答案 1 :(得分:0)

如果您的列已修复,您可以遍历" Desc"列然后复制将其他列的值设置为列的值" Cost"。

Sub SortMyColumns()

    Dim lastRow As Long
    Dim i As Long

    Dim costColumn As Integer
    Dim descColumn As Integer
    Dim billColumn As Integer
    Dim carColumn As Integer
    Dim rentColumn As Integer
    Dim taxColumn As Integer

    'Change values according to columns
    costColumn = 1
    descColumn = 2
    billColumn = 3
    carColumn = 4
    rentColumn = 5
    taxColumn = 6

    lastRow = Worksheets(1).Cells(Rows.Count, descColumn).End(xlUp).Row

    'Loop through the "Desc" column and check values
    For i = 1 To lastRow
        If Worksheets(1).Cells(i, descColumn).Value = "Bill" Then
            Worksheets(1).Cells(i, billColumn).Value = _
                Worksheets(1).Cells(i, costColumn).Value
        End If
    Next i
End Sub

这仅适用于您的列始终保持不变的情况。

VLOOKUP不起作用,因为列的顺序错误。成本应该在描述VLOOKUP工作之后。 VLOOKUP无法向左看。