![](/img/trans.png)
[英]copy a table from one Sheet and paste it in the next empty row of another Sheet using VBA excel
[英]Copy a column from one sheet and paste as row in another using application worksheetfunciton match in vba
我在Sheet1中有以下excel文件:
A B C D
Brand Model Type No_of_unit_sold
A AB123 1 1
A AB124 1 2
A AB125 1 11
A AB113 1 21
A AB127 1 42
A AB128 1 12
B BB123 1 21
B BB121 1 32
AB BB122 2 21
AB BB124 1 79
AB BB125 2 61
AB BB126 1 181
B BB127 1 28
B BB128 1 132
C CB121 1 91
C CB122 1 73
C CB123 1 63
C CB124 1 52
C CB125 1 85
A AB129 2 12
C CB126 1 13
C CB128 1 94
C CB129 1 121
我需要VBA首先掃描類型1的“類型”列。
然后,要查找品牌,請復制品牌A的名稱,總結出售的單位數並將其粘貼到Sheet2中:
A B C D E
Brand A B AB C
No_of_unit_sold 89 213 260 592
總結價值,我可以使用具有雙重條件的sumif函數。 但是,如何更改品牌名稱? 這不像將for循環用於整數一樣,就像我可以為“ Type”列做的事情一樣。
另外,如何在不重復的情況下將商標名稱從sheet1復制到sheet2? 我是否使用application.worksheetfunction.match? 例如。 如果在工作表2的單元格(1,i)中找不到品牌名稱,請從工作表1復制到工作表2?
下面的代碼將為您工作。 我已經使用了兩個For
循環, If
語句和Function
來實現這一點,因為application.worksheetfunction.match
不了解。 我嘗試如下並為我工作!
輸入表:
試試下面的代碼。
Sub VBAReader()
Dim CompareBrand As String
'Dim CompareBrands() As Variant
Dim Types, units, Units_sold, ValidatedBrands As Integer
Units_sold = 0
Dim Brand As String
Dim i, j, k, l As Integer
k = 2
Types = Worksheets("Sheet1").Range("C2").End(xlDown).Row
For i = 2 To Types
'Give the type of value
If Worksheets("Sheet1").Range("C" & i).Value = 1 Then
Brand = Worksheets("Sheet1").Range("A" & i).Value
If BrandIsValidated(Brand) = False Then
For j = 2 To Types
If Worksheets("Sheet1").Range("A" & j).Value = Brand And Worksheets("Sheet1").Range("C" & j).Value = 1 Then
units = Worksheets("Sheet1").Range("D" & j).Value
Units_sold = Units_sold + units
End If
Next
Worksheets("Sheet2").Cells(1, k).Value = Brand
Worksheets("Sheet2").Cells(2, k).Value = Units_sold
Units_sold = 0
CompareBrand = Worksheets("Sheet2").Cells(1, k).Value
k = k + 1
End If
End If
Next
End Sub
Function BrandIsValidated(stringToBeFound As String) As Boolean
ValidatedBrands = Worksheets("Sheet2").Cells(1, Columns.Count).End(xlToLeft).Column
For l = 1 To ValidatedBrands
If stringToBeFound = Worksheets("Sheet2").Cells(1, (l + 1)).Value Then
BrandIsValidated = True
Exit For
Else
BrandIsValidated = False
End If
Next
End Function
輸出表:
注意:我是VBA的新手,所以我的代碼不會友好。 歡迎編輯:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.