Excel VBA Cycle For - vba

I have a file named vegetables_fruits and 4 other files : apple, banana, tomato, cucumber. In the file vegetables_fruits I have a Worksheet named List where I fold the names of all 4 files (ex., cell A2 = apple, cell A3 = banana, cell A4 = tomato, cell A5 = cucumber). In addition to the sheet List I have sheets banana, tomato and cucumber, but I don't have apple.
It's necessary to paste the column A from each of this 4 files to every sheet in the vegetables_fruits (ex., from file apple it's necessary to copy column A to file "vegetables_fruits" to sheet "banane" ; from file "banana" it's necessary to copy column A to file vegetables_fruits to sheet tomato etc.) Thank you very much for your help!
P.S. It needs to create a For, but I don't know how I can decribe all of this conditions.
Sub CopyPaste()
Dim r As Variant
Dim a As Variant
Dim b As Integer
Dim nbcells As Integer
Dim ws As Worksheet
Worksheets("List").Activate
nbcells = Application.WorksheetFunction.CountA(Range("A2:A" & Range("A65536").End(xlUp).Row))
' === Create a new sheet ===
For r = 2 To nbcells
Sheets.Add After:=Sheets(Sheets.Count - 1)
Worksheets(r).Name = Worksheets("List").Cells(r + 1, 1).Value
Next r
' === DATA ===
For Each ws In Sheets
If ws.Name Like "*.xls*" Then
For a = 2 To nbcells
Windows(a).Activate
Range("B:B").SpecialCells(2).Copy
Workbooks("vegetables_fruits.xlsm").Activate
b = a + 1
If ws.Name = Worksheets("List").Cells(b, 1).Value Then
ws.Select
Range("A2").Select
ActiveSheet.Paste
End If
Next a
End If
Next
End Sub

Maria - Reading your question, I think the additional logic you need is as follows:
Assume all workbooks are open, and have the appropriate name.
Loop through all of the workbooks.
If I find a workbook with one of my defined names, then copy Column A from (some sheet) in that workbook
Paste this into the master workbook, on the sheet with the corresponding name.
For my example, you would need to add these variables in the section where the variables are declared.
Dim fromWS As Worksheet, toWS As Worksheet
Dim wb As Workbook, myWB As Workbook
Early in the code, near the top, you will need this line of code.
Set myWB = ActiveWorkbook
Later in the code, this Loop and Case statements will accomplish the above logic ...
For Each wb In Workbooks
Select Case wb.Name
Case "apple"
Set fromWS = wb.Worksheets("Sheet1") '<~~ put your sheet name here
Set toWS = myWB.Worksheets("apple")
Case "banana"
Set fromWS = wb.Worksheets("Sheet1") '<~~ put your sheet name here
Set toWS = myWB.Worksheets("banana")
Case "tomato"
Set fromWS = wb.Worksheets("Sheet1") '<~~ put your sheet name here
Set toWS = myWB.Worksheets("tomato")
Case "cucumber"
Set fromWS = wb.Worksheets("Sheet1") '<~~ put your sheet name here
Set toWS = myWB.Worksheets("cucumber")
Case Else
End Select
fromWS.Range("A:A").Copy toWS.Range("A:A")
Next wb
You talk about there not being an "apple" sheet. This is a nuance you may need to build exception logic for. (e.g. just omit that case in the above loop)

Related

Excel VBA Copy specific Column from different Worksheets

I'm currently developing a monitoring Tool in Excel using VBA and encountered some difficulties when copying data.
Current Code:
Sub CopyID()
'Copies entire Row of IDs from "Sheet 2" to main Sheet "Main Sheet"
Dim lastCell As Long
LastCell = Cells(Rows.Count,'Sheet 2':M).End(xlUp).Row
'Missing here: Copy to Column 1 at Row 3!
Sheets("Sheet 2").Columns(M).Copy Destination:=Sheets("Main Sheet").Columns(1)
End Sub
What it is supposed to do:
Copy the Data of Sheet2_Column M starting at Row 2
to
Main Sheet Colum A sarting at Row 3
Also, I don't know if this is possible yet, use a specific formula for the destination (Formular is: =LEFT(Data,10))
I am glad for any response to this as I'd like to learn how these "Copy Methods" work in detail and am happy for any tipps and tricks regarding these methods.
Edit//
The Copy Part should work like this
Sheet 2 Contains a Colum that has a headercell and X cells with a value that has a similar format.
Example of the Sheet 2 Contents
This is a row in Sheet 2. I only need the first 10 digits of the content of the cells. Is it possible to include that as a formula similar to
=Left(Sheet 2:M2,10)
so it works like this:
"sheet 2" cell content: "1234567891_1_123X" copy to "main sheet" as "1234567891"
Define your source and destination worksheet. And range/column names bust be submitted as strings like "M".
Sub CopyID()
'Copies entire Row of IDs from "Sheet 2" to main Sheet "Main Sheet"
Dim WsSource As Worksheet
Set WsSource = ThisWorkbook.Worksheets("Sheet 2")
Dim WsDestination As Worksheet
Set WsDestination = ThisWorkbook.Worksheets("Main Sheet")
Dim lastRow As Long
lastRow = WsSource.Cells(WsSource.Rows.Count, "M").End(xlUp).Row
'Missing here: Copy to Column 1 at Row 3!
WsSource.Range("M2:M" & lastRow).Copy Destination:=WsDestination.Range("A3")
End Sub
Edit:
To copy only the first 10 characters of each cell would need a process for each value:
Option Explicit
Public Sub CopyID()
'Copies entire Row of IDs from "Sheet 2" to main Sheet "Main Sheet"
Dim WsSource As Worksheet
Set WsSource = ThisWorkbook.Worksheets("Sheet 2")
Dim WsDestination As Worksheet
Set WsDestination = ThisWorkbook.Worksheets("Main Sheet")
Dim lastRow As Long
lastRow = WsSource.Cells(WsSource.Rows.Count, "M").End(xlUp).Row 'Find last row in column M
Dim ArrSource As Variant
ArrSource = WsSource.Range("M2:M" & lastRow).Value 'read column m values into array
Dim i As Long
For i = 1 To UBound(ArrSource) 'process each value in the array
ArrSource(i, 1) = Left$(ArrSource(i, 1), 10) 'keep only left 10 characters
Next i
WsDestination.Range("A3").Resize(UBound(ArrSource), 1).Value = ArrSource 'write array into destination
End Sub
Note .Resize(UBound(ArrSource), 1) defines the destination the same size as the array is that we want to insert.

VBA Excel: change offset based on active sheet

I'm trying to figure out how i can make a offset based on the Active sheet number.
Example:
Right now in sheet number 2 in Cell "B1" I have a number set of 17000
On the same sheet at B8:B I have a column of numbers going down with certain values that I would like to add up to my base of 17000. Once I make a new sheet I want "A1" To have that value of the other 2 numbers added up.
I have a Code that "Fills in" The active sheet that I'm using.
But how could I make it that in each new sheet it will go 1 position down in column B8:B
So sheet 2 has the values that will be used.
New sheet nmbr 5 gets created which will need sheet 2 "B1" + "B8"
New sheet nmbr 6 gets created which will need sheet 2 "B1" + "B9"
New sheet nmbr 7 gets created which will need sheet 2 "B1" + "B10"
And so on and so on.
Sub KnopKlik()
Dim WB As Workbook
Dim WS1 As Worksheet
Dim WS2 As Worksheet
Dim WS3 As Worksheet
Dim Active As Worksheet
Dim Titel1
Dim Titel2
Set WB = ActiveWorkbook
Set WS1 = WB.Sheets(1)
Set WS2 = WB.Sheets(2)
Set WS3 = WB.Sheets(3)
Set Active = WB.ActiveSheet
Set MC = Active.Range("B9")
Titel1 = WS2.Range("B1") 'Base number of 17000
Titel2 = WS2.Range("B8") 'Has to be added up to 17000 depending on sheet number
column1 = Sheets(3).Cells(1, 3).Value
Application.ScreenUpdating = False
'============================================================
Sheets(1).Visible = True ' Activate Sheets
Sheets(2).Visible = True
Sheets(3).Visible = True
Active.Select
ActiveSheet.Range("A1").Value = "Unit " & (Titel1 + Titel2)
'This is the line that is suppose to write the question i asked.
'=============================================================================
' Between these lines is a bunch of code i left out cause its irrelivant to the question.
'=============================================================================
Application.ScreenUpdating = True
Active.Select
Sheets(1).Visible = xlVeryHidden
Sheets(3).Visible = xlVeryHidden
Sheets(4).Visible = xlVeryHidden
MsgBox ("Done")
End Sub
I hope the question isn't to hard to understand. I got what i want exactly in my head but i find it hard to explain in English :P
Ok, try
Titel2 = WS2.cells(4 + activesheet.index,2)

Export each row from Excel into its own Word Document

This is gonna be pretty specific.
I have an excel sheet with patient names and info in each row. The first row has the labels for each column. For instance, column a is PatientName. Im trying to export each row as their own word document with each cell in the row having its own line with a space/break between each. But I also want the label from row 1 to be with each specific row. Also make the first column aka PatientName the name for each document.
Ex.
Document Name: John Doe
Encounter Date
11-12-13
CC
Abdominal Pain
HPI
Mr. Doe is blah blah, and bunch of text
\Ex
Row #1 looks like:
PatientName/EncounterDate/CC/HPI
Row#2 which is where we wanna start looks like:
John Doe/11-12-13/Abdominal Pain/Mr. Doe blah blah
Each row has 27 cells
Thanks, and let me know if you need anymore info. VBA code.
Edit: This was the code I was using, but It makes each file into an Excel sheet and doesn't add row 1 with each row.
Sub SaveRowsAsCSV()
Dim wb As Excel.Workbook, wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim r As Long, c As Long
Set wsSource = ThisWorkbook.Worksheets("AmazingChartsEncounters")
Application.DisplayAlerts = False 'will overwrite existing files without asking
r = 1
Do Until Len(Trim(wsSource.Cells(r, 1).Value)) = 0
ThisWorkbook.Worksheets.Add ThisWorkbook.Worksheets(1)
Set wsTemp = ThisWorkbook.Worksheets(1)
For c = 2 To 27 'I didn't test it when I changed the 7 here to 27
wsTemp.Cells((c - 1) * 2 - 1, 1).Value = wsSource.Cells(r, c).Value
Next c
wsTemp.Move
Set wbNew = ActiveWorkbook
Set wsTemp = wbNew.Worksheets(1)
'wbNew.SaveAs wsSource.Cells(r, 1).Value & ".csv", xlCSV 'old way
wbNew.SaveAs "textfile" & r & ".csv", xlCSV 'new way
'you can try other file formats listed at http://msdn.microsoft.com/en-us/library/office/aa194915(v=office.10).aspx
wbNew.Close
ThisWorkbook.Activate
r = r + 1
Loop
Application.DisplayAlerts = True
End Sub

Paste worksheet names in multiple worksheets

I have a workbook with over 50 worksheets. I would like to copy the name of each worksheet into a cell of that particular workbook. I can do it for one sheet at a time using a macro with the following VBA code:
Range("B1") = ActiveSheet.Name
But when I try to apply the macro to several worksheets at a time, it fails. I would like it to get the names of the first 30 worksheets only.
Avoid relying on the ActiveSheet property to identify the worksheet you want to process. The With ... End With statement can readily provide the worksheet and help retrieve the Worksheet .Name property.
Sub name_Worksheets()
Dim w As Long
For w = 1 To 30
With Worksheets(w)
.Cells(1, 2) = .Name
End With
Next w
End Sub
See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.
My Understanding is you want to 1) Go through first 30 sheets of your workbook and 2) Paste the sheet name into cell B1.
Sub PasteSheetNameInB1()
For i = 1 To 30 '(1 to 30 because you said " I would like it to get the names of the first 30 worksheets only.")
ActiveWorkbook.Sheets(i).Select 'Iterates through first 30 sheets
Range("B1") = ActiveSheet.Name 'Pastes Sheet name into B1
Next i
End Sub
You can use this code:
For i = 1 To 30
Sheets(i).Range("B1").Formula = "=MID(CELL(""filename"",A1),FIND(""]"",CELL(""filename"",A1))+1,255)"
Next
Now if you change the name of any worksheet, You don't need to run the macro again, the formula in Rnage("B1") will display the new name.
So with this code, that you'll paste in the destination workbook,
you'll just need to change :
workbook_to_scan's Name and
Sheet's name in which to paste the names
to fit your needs!
Sub test_johnB()
Dim wB1 As Workbook, _
wB2 As Workbook, _
wSDest As Worksheet, _
wS As Worksheet, _
i As Integer
Set wB1 = ThisWorkbook
Set wB2 = Workbooks("workbook_to_scan's Name")
Set wSDest = wB1.Sheets("Sheet's name in which to paste the names")
i = 0
For Each wS In wB2.Sheets
wSDest.Range("B1").Offset(i, 0) = wS.Name
Next wS
End Sub

Create Sheets from list in excel using template

I have an excel template (//desktop/spellTemplate.xltx) Now I have a worksheet open with a list of names starting at A2 and a description at A3
A2 A3
Imp does 5 damage
death does 3 damage
ghost heals 5 life.
The list is quite long and i need to do two things with this list.
First how can i create a new worksheet (in this workbook) for each of the items in the A2 collumn, with the worksheet named after the item.I
Now when it creates the new worksheet, I want it to use the template i created above.
Then put the name A2 into the templates cell A1 and the descriptionA3 into the templates cell C1. How can I can do this all automatically for the list of names?
I assumed your list looks like the following and is on a sheet named Spells:
Try running this code by changing the path to the location of your template file:
Sub createSheet()
Dim rng As Range
Set rng = Sheets("Spells").Range("A2:A4")
Dim wks As Worksheet
For Each cell In rng
On Error Resume Next
If cell.Value <> "" Then
Set wks = Sheets.Add(After:=Worksheets(Worksheets.Count), Type:="C:\Users\PortlandRunner\AppData\Roaming\Microsoft\Templates\spellTemplate.xltx")
wks.Name = cell.Value
wks.Range("A1").Value = cell.Value
wks.Range("C1").Value = cell.Offset(0, 1).Value
End If
Next cell
End Sub
The On Error Resume Next line will skip sheets that already exist.
Resulting sheets created: