How to paste on colunm based on its name - excel

I have this code to paste content in my table, but I want it to work correctly when I'm not in a specific cell in the current row, because it always returns a fixed cell number to paste the content, so I would like help to know how I modify this code so that it pastes the contents in the current line but instead of using ActiveCell.Offset(0, -3) , use something that would: Paste in the cell of the current row that is part of the column [Plano de Contas].
My current code:
Sub COLAR_CC()
ActiveCell.Offset(0, -3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=False
End Sub
Table for reference:

I think this may start you off:
Option Explicit
Sub sub1()
Dim icol&
icol = FindCol("ColTwo") ' find column
Cells(3, icol) = "Got it"
End Sub
Function FindCol&(txt$) ' find column
Dim iErr&
On Error Resume Next
FindCol = Rows(1).Find(txt, , xlValues, xlWhole, xlByColumns, xlNext, True).Column
If Err.Number <> 0 Then Stop ' handle error
On Error GoTo 0
End Function

Related

copy and paste based on certain conditions

i need a simple vba code. I hope someone can help me.
So, I want to copy the range B2:E6 and leave some cells marked with a special condition. I created a rule in cells A2:A6 with the value Y / X. In the end, I want to paste the value B2:E6 in the range F9:I13 only if the value is Y.
I am attaching the following image to make it easier for you to understand.
Any help will be great. And sorry my english is bad.
Maybe this can get you started
Sub Macro1()
Dest = 8
For Row = 1 To 6
If Cells(Row, 1) <> "x" Then
Range(Cells(Row, 2), Cells(Row, 5)).Select
Selection.Copy
Cells(Dest, 6).Select
ActiveSheet.Paste
End If
Dest = Dest + 1
Next Row
End Sub
I recommend that you first define your working worksheet, if the CommandButton1 button code linked to the CommandButton1_Click() event, showen in your code, is not associated with your working sheet (Sheet9). Otherwise, the code will be executed on another Sheet than Sheet9, on which you want the conditions to be fulfilled.
So, I suggest this code, that formats also the target table "(F8:I13)":
Private Sub CommandButton1_Click()
Dim myWorkingSheet As Worksheet
Dim Working_Range As Range, Target_Range As Range
Dim Line_to_Read As Double, Table_Shift As Double
Set myWorkingSheet = Sheets("Sheet9")
myWorkingSheet.Activate
' Copy the header table
myWorkingSheet.Range("B1:E1").Copy Range("F8")
Application.CutCopyMode = False
' Copy the format of the table
myWorkingSheet.Range("B1:E6").Copy
myWorkingSheet.Range("F8").PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
' Copy table if current cell in column A = "y"
Set Working_Range = myWorkingSheet.Range("A2:A6")
Line_to_Read = 2
Table_Shift = 7 'To start at F9 cell
For Each wr In Working_Range
If wr = "y" Then
myWorkingSheet.Range(Cells(Line_to_Read, 2), Cells(Line_to_Read, 5)).Copy myWorkingSheet.Range(Cells(Line_to_Read + Table_Shift, 6), Cells(Line_to_Read + Table_Shift, 10))
End If
Line_to_Read = Line_to_Read + 1
Next
' To point the cursor at the first cell.
myWorkingSheet.Cells(1, 1).Select
End Sub
To avoid the repetition of myWorkingSheet in the you use With clause and End With.

Searching with a Macro/VBA Using a Cell reference

This is probably a really easy thing that I am screwing up. I am working on a school project Creating an Inventory sheet.
My "Inventory" sheet has a bunch of product info on it.
My "Add Inventory" Sheet is set up with a VLOOKUP so when I scan my bar code it displays the row of information from the "Inventory sheet"
I made a macro button and recorded a Macro to try to edit the available inventory by clicking the button.
This is what I recorded.(the original I slaughtered trying to edit it but this should be the same)
Sub Macro7()
'
' Macro7 Macro
'
'
Sheets("Add Inventory").Select
Range("B5").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Inventory").Select
Cells.Find(What:="764666143326", After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Range("K15").Select
Sheets("Add Inventory").Select
Range("K13").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Inventory").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("L15").Select
End Sub
So my problem is the macro records the What:="764666143326" for the search with the bar code I was using for a sample. I need it to use the new bar code I scan on the next run. So I need it as a variable or to refence a cell. So I believe I need to set a Dim and a Range but have tried many times and watched a ton of videos with no success. I normally only use the record Macro button and don't not edit the VBA code. Please Help Me!!
EDIT:
Everying on this sheet is filled with VLOOKUP or a formula, except the yellow Cell B5, I scan the bar code into that cell.
Add Inventory sheet
This is the page I want to edit with the Macro/VBA. I want it to search column C for the Bar code number I scanned into the "Add Inventory" sheet (which will change depending on what I am adding) and when it finds the matching bar code I want it to edit the "Quantity in Stock" or column K for that row of the matching bar code.
Inventoy sheet
My problem is the macro I recorded saves what ever barcode I used for it not the cell as a variable.
Edit # 2
I think this show closer to what I am trying to do
Sub Macro7()
'
' Macro7 Macro
'
'
Sheets("Add Inventory").Select
Range("K13").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Inventory").Select
Cells.Find(What:=Range("A1"), After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate.Offset(0, 8).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Add Inventory").Select
Range("B5").Select
End Sub
For this one I made Inventory cell A1 = ='Add Inventory'!B5
Also My bar codes are 12 digits.
Update Inventory
Option Explicit
Sub addNewQuantity()
' Write lookup value (Bar Code) to a variable.
Dim lValue As Long: lValue = Range("B5").Value
' Define range (to look for Bar Code).
With ThisWorkbook.Worksheets("Inventory")
Dim fCell As Range: Set fCell = .Range("C4")
Dim lCell As Range: lCell = .Range(.Rows.Count, fCell.Column).End(xlUp)
Dim rg As Range: Set rg = .Range(fCell, lCell)
End With
' Attempt to find the index (row) of a match.
Dim cIndex As Variant: cIndex = Application.Match(lValue, rg, 0)
If IsNumeric(cIndex) Then
' Write new value to column 'K' (8 cells to the right from column 'C').
rg.Cells(cIndex).Offset(, 8).Value = Range("K13").Value
MsgBox "Bar Code ID '" & lValue & "' updated.", vbInformation, "Success"
Else
MsgBox "Bar Code ID '" & lValue & "' not found.", vbCritical, "Failure"
End If
End Sub
Unfortunately I think there is a bigger problem with this method recorded by the macro recorder - this code will always select range "K15" regardless of what you search for.
I recommend you do not use the macro recorder, among other reasons it often creates code full of semantic errors - i.e. it works and it does does exactly what you tell it to do, which may not be the same as what you want it to do! As in the example above.
I would try something like this (you will need to check that the worksheets, ranges and column numbers in the code below are correct for your project):
First we declare and assign a worksheet object, referring to your Inventory worksheet:
dim ws as worksheet
set ws = Sheets("Inventory")
Then we need to loop through every row on this worksheet and if the value in the barcode column matches a given search parameter, increase the value in the stock level column on that row, by the value of another cell on another sheet.
For this we will need a counter for the loop:
dim counter as integer
the search parameter:
dim searchParam as variant
searchParam = Sheets("Add Inventory").Range("B5").value
and the new value we want added to the current stock level:
dim newValue as variant
newValue = Sheets("Add Inventory").Range("K13").value
we need to tell Excel which column number to search in and which to change, I assumed you are adding stock to the inventory. You will need to change the column numbers below to suit your project
Dim barcodeColumnNumber As integer
Dim stockColumnNumber As integer
barcodeColumnNumber = 1
stockColumnNumber = 2
Now we add the loop
For counter = 1 To ws.UsedRange.Rows.Count
if ws.Cells(counter, barcodeColumnNumber) = searchParam then
ws.Cells(counter, stockColumnNumber) = ws.Cells(counter, stockColumnNumber) + newValue
End If
Next counter

Excel VBA loop code

I need help with loop code to copy one cell from column R and paste into next empty cell in column C.
column C
12345
12345
12345
(paste 1 in here)
12346
12346
(paste 2 in here)
12347
12347
12347
12347
(paste 3 in here)
Column R
1
2
3
I used this code but when I will have 500 records it seems impossible to repeat this code for 500 times.
Range("R2").Select
Selection.Copy
Range("C1").Select
If IsEmpty(ActiveCell.Offset(1, 0)) Then
ActiveCell.Offset(1, 0).Select
Else
ActiveCell.End(xlDown).Offset(1, 0).Select
End If
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Try this:
Option Explicit
Public Sub CopyAndPaste()
Dim colToPaste As New Collection
Dim rngCell As Range
With Worksheets(1)
For Each rngCell In .Range("B1:B5")
colToPaste.Add rngCell
Next rngCell
For Each rngCell In .Range("A1:A500")
If IsEmpty(rngCell) Then
If colToPaste.Count = 0 Then Exit Sub
rngCell = colToPaste(1)
colToPaste.Remove (1)
End If
Next rngCell
End With
End Sub
In general, this is what we have:
a collection colToPaste, which contains all the values of the range B1:B5. You can change the collection range and make it with variable, as per the last row in column B. See here - https://www.rondebruin.nl/win/s9/win005.htm
A loop going through the range A1:A500, which would check for every cell, whether it is empty or not. If it is empty, it would give it the value of the first one in the list like this - rngCell = colToPaste(1). Then it would remove it.
In order to know when to stop, I have added If colToPaste.Count = 0 Then Exit Sub. The =0 part can be removed, but it is easier to understand it this way.

Row reference in InputBox?

here's the code I currently have in VBA (Excel) at the moment. Most of it has come from macro recordings that I've made. What I'm looking for is to be able to insert for example, row 10 as just 10 in the inputbox without having to put it in as 10:10. Is there a way for me to edit my current code to allow this? I've tried using Rows("TargetRow:TargetRow") but that gives odd results.
Dim TargetRow As Variant
TargetRow = InputBox("Insert row # where data should be inserted. This should take the format XX:XX (e.g. 90:90 for row 90)", "All Industries Row", "XX:XX")
wbThis = ThisWorkbook.Name
Windows(wbThis).Activate
Rows(TargetRow).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromAbove
Windows("otherworksheet.xlsx").Activate
Range("A119:J119").Select
Application.CutCopyMode = False
Selection.Copy
Windows(wbThis).Activate
Range(TargetRow).Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Use following sub to select rows using inputbox
Sub SelectRow()
Dim lnRow As Long
lnRow = InputBox("Enter Row number.", "Row Input")
Rows(lnRow & ":" & lnRow).Select
End Sub
If you need a Range from user input, the simplest way is to use the Excel version Application.InputBox with a type of '8' (see the documentation here).
Dim TargetRow As Range
Set TargetRow = Application.InputBox("Select the row where data should be inserted.", _
"All Industries Row", , , , , , 8)
Debug.Print TargetRow.Address
Note that you should probably also get rid of the Select and Activate calls and use your object references directly.

VBA Excel - Avoid not exsisting rangenames when copy/paste data from one rangename to another rangename

From cells in a sheet (Sheets("Omrnavne")) with several Range names written below each other the code has to find the first value (range name) written, find and select the actual range with this name on Sheets("Specifikationer"), copy data, go to the next value on Sheets("Omrnavne"), find the actual range, paste values and start over.
Problem: if there is written a range name on Sheets("Omrnavne") that don't exist as range name how do one skip this?
With the following code: If Range(whatToFind) Is Nothing Then
I get the error:
Run-time error '1404': Method 'Range' of object'_Global' failed
when searching for a rangename that dosen't exist.
I've tried for hours but with no success. Please help - thanks.
The code is:
Sub Test1()
Dim whatToFind As String
Sheets("Omrnavne").Select
' Select first line of data*.
Range("a1").Select
' Set Do loop to stop when an empty cell is reached.
Do Until IsEmpty(ActiveCell)
whatToFind = ActiveCell.Value
'Find rangename, select and copy
Sheets("Specifikationer").Select
With Sheets("Specifikationer")
On Error Resume Next
On Error GoTo 0
If Range(whatToFind) Is Nothing Then ' <~~~~ ERROR HERE
Sheets("Omrnavne").Select
ActiveCell.Offset(2, 0).Select
whatToFind = ActiveCell.Value
Else
Range(whatToFind).Select
Selection.Copy
End If
End With
' Find and select rangename to paste to
Sheets("Omrnavne").Select
With Sheets("Omrnavne").Select
ActiveCell.Offset(1, 0).Select
whatToFind = ActiveCell.Value
Sheets("Specifikationer").Select
Range(whatToFind).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
End With
' Step down 1 row from present location.
Sheets("Omrnavne").Select
ActiveCell.Offset(1, 0).Select
Loop
End Sub
As you have seen already, the ActiveSheet.Range property returns not Nothing, if the range does not exists. Instead it will produce an error. You can DIM an object variable as Range. This variable is Nothing until it is setted. Then you can try setting this variable to the named range within an error handling block. If the variable is further Nothing after this, then the named range not exists.
Example:
Dim oRange As Range
On Error Resume Next
Set oRange = Range("test")
On Error GoTo 0
If oRange Is Nothing Then
MsgBox "No range named ""test"" present."
Else
MsgBox oRange.Address
End If
Greetings
Axel

Resources