I am new to macros, please help me in the below scenario issue
Scenario
NOTE - Columns selection from source and target are dynamic
Issue
Below is my script,the issue is while pasting the dynamic selected column from source to result sheet it is pasting the data in column which are given input in source. Example - while pasting the C,G,F from source to result sheet it is pasting the data in columns C,G,F of result instead pasting in the next empty column(B,C,D).
In the below script "Worksheets("Result").Cells(Rownum, ch) = Column_source_value" is causing this issue, please help me how i need to change Cells parameters
Code
Dim ws1lastrow As Long, ws2lastrow As Long, ws1lastcolumn As Integer, ws2lastcolumn As Integer
Dim maxRow As Integer, maxColumn As Integer
Dim i As Integer, j As Integer, k As Integer, x As Long, Column_source As String, Column_target As String
Dim sourceValue As String
Dim targetvalue As String
Dim addsourcecolvalue As String, ch As Variant, AddColumn_source_num As String, AddColumn_source_value As String
Dim addsourceValue() As String
Sub Compare()
CompareWorksheets Worksheets("Source"), Worksheets("Target")
End Sub
Sub CompareWorksheets(ws1 As Worksheet, ws2 As Worksheet)
sourceValue = Sheets("Source").TextBox1.Value
targetvalue = Sheets("Source").TextBox2.Value
addsourcecolvalue = Sheets("Source").TextBox3.Value
With ws1.UsedRange
ws1lastrow = .Rows.Count
ws1lastcolumn = .Columns.Count
End With
With ws2.UsedRange
ws2lastrow = .Rows.Count
ws2lastcolumn = .Columns.Count
End With
maxRow = ws1lastrow
maxColumn = ws1lastcolumn
For i = 1 To ws1lastrow
For j = 1 To ws2lastrow
Column_source_num = sourceValue & i
Column_target_num = targetvalue & j
Column_source_value = Worksheets("Source").Range(Column_source_num).Value
Column_target_value = Worksheets("Target").Range(Column_target_num).Value
If Column_source_value = Column_target_value Then
Sheets("Source").Cells.Find(What:=Column_source_value, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False).Activate
Dim Rownum As String
Rownum = ActiveCell.Row
Worksheets("Result").Cells(i, 1) = Column_source_value
splitsourcecloumn (Rownum)
End If
Next j
Next i
End Sub
Function splitsourcecloumn(Rownum)
addsourceValue() = Split(addsourcecolvalue, ",")
For Each ch In addsourceValue()
Column_source_num = ch & Rownum
Column_source_value = Worksheets("Source").Range(Column_source_num).Value
Worksheets("Result").Cells(Rownum, ch) = Column_source_value
Next ch
End Function
Try using this function to find the first unused column.
Public Function GetLastColumn() As Long
If WorksheetFunction.CountA(Cells) > 0 Then
GetLastColumn = Cells.Find(What:="*", _
After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
End If
End Function
I hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.