Creating a macro that copies certain cells and places them into columns - vba

I have 26 worksheets every week that contain a "Station #", "Latitude#", and a "Longitude#".
I want to create a Macro that grabs these 3 cells, copies them and places them into 3 columns named "Station #", "Lat", and "Long.
I'm not very good at this so i need some help.
This is what i got so far:
Sub Macro1()
FolderName = "C:\Users\Captain Wypij\Desktop\Traffic\test"
If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
Fname = Dir(FolderName & "*.xls")
'loop through the files
Do While Len(Fname)
With Workbooks.Open(FolderName & Fname)
Range("C8:D8").Select
Selection.Copy
ChDir "C:\Users\Captain Wypij\Desktop\Traffic"
Workbooks.Open Filename:= _
"C:\Users\Captain Wypij\Desktop\Traffic\Test.xls.xlsx"
Range("A2").Select
If ("A2") = "*" Then Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks.Open (FolderName & Fname)
ActiveWindow.SmallScroll Down:=12
Range("C34:D34").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Test.xls.xlsx").Activate
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks.Open (FolderName & Fname)
Range("G34:H34").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Test.xls.xlsx").Activate
Range("C2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks.Open (FolderName & Fname)
ActiveWindow.Close
Windows("Test.xls.xlsx").Activate
ActiveWorkbook.Save
ActiveWindow.Close
End With
' go to the next file in the folder
Fname = Dir
Loop
End Sub
I cant seem to figure out how to paste the next worksheet i open in the next fields ( such as A3, B3, C3 and so forth.
Please help me!

Try this:
Dim FolderName As String, Fname As Variant
FolderName = "C:\Location\Folder\"
Fname = Dir(FolderName & "*.xlsx")
Dim wb As Workbook, ws As Worksheet, lr as long
Do While Fname <> ""
Set wb = Workbooks.Open(FolderName & Fname)
Set ws = wb.Sheets("SheetName") '~~> Change to suit
With Thisworkbook.Sheets("Sheet1") '~~> Change to suit
lr = .Range("A" & .Rows.Count).End(xlUp).Row + 1
ws.Range("C8:D8").Copy: .Range("A" & lr).PasteSpecial xlPasteValues
ws.Range("C34:D34").Copy: .Range("B" & lr).PasteSpecial xlPasteValues
ws.Range("G34:H34").Copy: .Range("C" & lr).PasteSpecial xlPasteValues
End With
wb.Close False
Set wb = Nothing: Set ws = Nothing
Fname = Dir
Loop
Above code basically opens all .xlsx file in the specified folder and then copies static ranges. This static ranges are the ones you specified in your question (e.g. Range("C8:D8")). So it copies it and paste it as values on the sheet you will specify. It finds the last row on the destination sheet which will put the copied values below it.
Is this what you're trying? HTH.

Related

Deleting all input in the Name Manager after saving external workbook

I am currently making a macro which creates a catalogue and afterwards saves it in different languages as external files. Whenever I save the files with the VBA script below the file is still large (2MB+), but whenever I open the file and delete all references in the Name Manager (these are copied as well it seems), the file is just 30/40 kb.
Is there a VBA formula that automatically deletes the formulas in the Name Manager (only in the external copy, not in the original file!)?
Sub NIP_Version()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks("Opbouw catalogus.xlsm").Activate
filenaam = ActiveWorkbook.Path & "\" & "Excel prijslijst" & "\" & Sheets("Catalogus").Range("A1").Text & " " & Sheets("Catalogus").Range("G2").Text
'Quotation blad copy
Sheets("Catalogus").Select
'paste as values
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Dim LastRowNIP As Long
With ActiveSheet
LastRowNIP = .Cells(.Rows.Count, "E").End(xlUp).Row
End With
Set example = Range("A5:G" & LastRowNIP)
example.Value = example.FormulaR1C1
Columns("F").EntireColumn.AutoFit
'Save
Application.ScreenUpdating = True
Sheets("Catalogus").Range("A1").Select
ActiveSheet.Copy
ActiveWorkbook.Sheets("Catalogus").SaveAs Filename:=filenaam, FileFormat:=51
Application.DisplayAlerts = True
ActiveWorkbook.Close SaveChanges:=False
Sub remove_names()
Dim xName As Name
For Each xName In Application.ThisWorkbook.Names
xName.Delete
Next xName
End Sub
Sub NIP_Version()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks("Opbouw catalogus.xlsm").Activate
filenaam = ActiveWorkbook.Path & "\" & "Excel prijslijst" & "\" & Sheets("Catalogus").Range("A1").Text & " " & Sheets("Catalogus").Range("G2").Text
'Quotation blad Copy
Sheets("Catalogus").Select
'Paste as value
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Dim LastRowNIP As Long
With ActiveSheet
LastRowNIP = .Cells(.Rows.Count, "E").End(xlUp).Row
End With
Set example = Range("A5:G" & LastRowNIP)
example.Value = example.FormulaR1C1
Columns("F").EntireColumn.AutoFit
'Save
Application.ScreenUpdating = True
Sheets("Catalogus").Range("A1").Select
ActiveSheet.Copy
ActiveWorkbook.Sheets("Catalogus").SaveAs Filename:=filenaam, FileFormat:=51
Sub remove_names()
Dim xName As Name
For Each xName In Application.ThisWorkbook.Names
xName.Delete
Next xName
End Sub
Application.DisplayAlerts = True
ActiveWorkbook.Close SaveChanges:=False
Workbooks("Prijslijst maken.xlsm").Activate

Loop to insert picture in correspondingly named workbook

I am trying to insert the correct country map JPG in the correct country XLSX. By "correct" I mean there is one map for each XLSX - Albania.jpg into Albania.xlxs, Andorra.jpg into Andorra.xlxs, etc.
My macro is to do the following:
Enter country name and year in User Form worksheet cells B2 and B3 (works fine!).
Enter country population and income level in Countries worksheet cells B1 and E1 (works fine!).
Insert country map JPG in User Form worksheet at cell A18 (cannot get this to loop!).
Save the workbook as CountryName.xlxs (works fine!).
I have tried using Filename = Dir(Path & "*.jpg") and ActiveSheet.Pictures.Insert without success. I think I need to use ActiveSheet.Pictures.Insert because the cells above the map's position (cell A18) will expand and the map needs to move down.
Sub SaveCountryYear_XLSX_English_map()
Dim lRow, x As Integer
Dim wbName As String
Dim MapPath As String 'Not used in example below
Dim MapName As String 'Not used in example below
Dim index As Integer
Application.DisplayAlerts = False
Application.ScreenUpdating = False
lRow = Range("A" & Rows.Count).End(xlUp).Row
x = 1
Do
x = x + 1
Worksheets("Countries").Activate
'1. Enter country name and year in User Form worksheet cells B2 and B3.
Range("A" & x).Select
Selection.Copy
Sheets("User Form").Select
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Sheets("Countries").Select
Range("B" & x).Select
Selection.Copy
Sheets("User Form").Select
Range("B3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
'2. Enter country population and income level in Countries worksheet cells B1 and E1.
Sheets("Countries").Select
Range("C" & x).Select
Selection.Copy
Sheets("Table").Select
Range("B1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Sheets("Countries").Select
Range("D" & x).Select
Selection.Copy
Sheets("Table").Select
Range("E1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
'3. Insert country map JPG in User Form worksheet at cell A18
'(cannot get this to loop!).
'The following is just an example - it works,
'but without loop of course (inserts the named file correctly).
Sheets("User Form").Select
Range("A18").Select
ActiveSheet.Pictures.Insert( _
"C:\temp\profiles\2017\Maps\EN JPGs\Albania_EN.jpg").Select
Sheets("Countries").Select
'4. Save the workbook as CountryName.xlxs.
wbName = Range("A" & x).Value & "_" & Range("B" & x).Value & "_EN"
ActiveWorkbook.SaveAs Filename:="C:\temp\profiles\2017\Production\Batch_EN_1\" _
& wbName & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Loop Until x = lRow
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
edited after OP's clarifications
you may want to try this refactored code:
Option Explicit
Sub SaveCountryYear_XLSX_English_map()
Dim wbName As String
Dim MapPath As String 'Not used in example below
Dim MapName As String 'Not used in example below
Dim index As Integer 'Not used in example below
Dim cell As Range
Application.DisplayAlerts = False
Application.ScreenUpdating = False
With Worksheets("Countries") '<--| reference "Countries" worksheet of your currently active workbook
For Each cell In .Range("A2", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(XlCellType.xlCellTypeConstants, xlTextValues) '<--| loop through referenced worksheet column A cells filled with some text from A2 down to last not empty one
'1. Enter country name and year in User Form worksheet cells B2 and B3.
Worksheets("User Form").Range("B2").value = cell.value '<--| name is in current cell
Worksheets("User Form").Range("B3").value = cell.Offset(, 1).value '<--| date is in adjacent cell
'2. Enter country population and income level in Countries worksheet cells B1 and E1.
Worksheets("Table").Range("B1").value = cell.Offset(, 2).value '<--| population is in cell two columns right of current one
Worksheets("Table").Range("E1").value = cell.Offset(, 3).value '<--| income level is in cell three columns right of current one
'3. Insert country map JPG in User Form worksheet at cell A18
'(cannot get this to loop!).
'The following is just an example - it works,
'but without loop of course (inserts the named file correctly).
Worksheets("User Form").Activate
Range("A18").Select
ActiveSheet.Pictures.Insert _
"C:\temp\profiles\2017\Maps\EN JPGs\" _
& cell.value & "_EN.jpg"
'4. Save the workbook as CountryName.xlxs.
Worksheets.Copy '<--| copy current workbook worksheets to a new workbook
ActiveWorkbook.SaveAs Filename:="C:\temp\profiles\2017\Production\Batch_EN_1\" _
& wbName & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Close
Next cell
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
where:
you have to adapt:
ActiveSheet.Pictures.Insert _
"C:\temp\profiles\2017\Maps\EN JPGs\" _
& cell.value & "_EN.jpg"
to your actual filenames and source path conventions
I changed section 4 (Save the workbook as CountryName.xlxs)

Browse file path and should add it to Vlookup for Reference using VBA

Hi I need to be able to browse a file and add it in vlookup formula for reference using vba...here is my code...please help
I am able to pick a file, but the problem is double time opening of FileDialog folder for selection.
Private Sub CommandButton2_Click()
Range("Q2").Select
FilePath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xls")
If FilePath <> False Then
Range("D6").Value = FilePath
ActiveCell.FormulaR1C1 = _
"=VLookup(RC[-13]:R[68]C[-13],'FilePath'!R2C2:R994C6,5,False)"
Range("Q2").Select
Selection.Copy
Range("P2").Select
Selection.End(xlDown).Select
Selection.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Range("Q:Q").Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("Q1").Select
Selection.Value = "Payment Method"
Range("Q2").Select
Dim AutoRange As Range
Dim i As Long
Set AutoRange = Range("Q:Q")
For i = 1 To 8000
If AutoRange.Cells(i).Value = "0" Then
AutoRange.Cells(i).Value = "Online"
Else
End If
Next i
ActiveWorkbook.Save
End Sub
I think you are forgetting to name the worksheet from where you want yo search your information in your vlookup formula. Let's assume the data is stored in "sheet1" for every workbook that is eligible:
FilePath_final = Left(FilePath, InStrRev(FilePath, "\")) + "[" + Right(FilePath, Len(FilePath) - InStrRev(FilePath, "\")) + "]"
' That is to put the "[" and "]" before and after the workbook name
ActiveCell.FormulaR1C1 = _
"=VLookup(RC[-13]:R[68]C[-13],'" + FilePath_final + "sheet1'!R2C2:R994C6,5,False)"
Try those 2 lines instead of your vlookup line

Splitting and Hardcoding worksheets containing pivot tables

I am new to using VBA code. I have a workbook with manually created tables as well as pivot tables. For each worksheet in this book, I want to hard-code the data into a new workbook and save it as the name of the worksheet that is being hard-coded. I have the code below. It is saving each workbook properly, but the contents of the workbook are not correct. It is hard-coding the contents of the first worksheet in my original workbook every time. I've tried to set the next ActiveSheet at the end of the code but it fails. Did I mention I am not a programmer? Please help!
Sub Splitbook()
Dim path As String
Dim dt As String
path = CreateObject("WScript.Shell").specialfolders("Desktop") & "\SLF\ "
Call Shell("explorer.exe" & " " & path, vbNormalFocus)
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ActiveSheet.UsedRange.Select
Selection.Copy
Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveWorkbook.SaveAs path & ws.Name, Excel.XlFileFormat.xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=False
Next ws
End Sub
You already have the code looping through the sheets of your workbook so you do not need to copy from the ActiveSheet but from the ws worksheet variable.
You also do not need to use Select to get data copied.
Dim ws As Worksheet
Dim newBook As Workbook
For Each ws In ThisWorkbook.Worksheets
ws.UsedRange.Copy
Set newBook = Workbooks.Add
With newBook.Worksheets(1).Range("A1")
.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End With
newBook.SaveAs Path & ws.Name, Excel.XlFileFormat.xlOpenXMLWorkbook
newBook.Close SaveChanges:=False
Next ws

Excel VBA code, one macro works when ran by itself, but debugs when ran in a group

My program works by calling a number of macros as such:
Sub Start()
Call ClearAll
Call Sales_Download
Call Copy_Sales
Call Receipt_Download
Call Copy_Receipt
Call Copy1
Call Sales_Summary
Call Copy2
Call Receipt_Summary
End Sub
My program breaks at the copy2, which is essentially an exact replica of copy1 wich works fine. When copy2 is ran by itself it works perfectly, but when I attempt to run the entire program it debugs. The bolded line is where the debug happens.
Sub Copy2()
' Copies all data from Receipt Download tab for each location, and saves in a seperate folder
Dim i As Long
Dim lngLastRow As Long, lngPasteRow As Long
'Find the last row to search through
lngLastRow = Sheets("Receipt_Download").Range("J65535").End(xlUp).Row
'Initialize the Paste Row
lngPasteRow = 2
Dim rng As Range
Dim c As Range
Dim endrow
Dim strName As String
Dim ws As Worksheet
Dim j As Long
endrow = Sheets("names").Range("A65000").End(xlUp).Row
Set rng = Sheets("names").Range("A2:A" & endrow)
j = 1
FBO = strName
For Each c In rng
For i = 2 To lngLastRow
strName = c.Value
If Sheets("Receipt_Download").Range("J" & i).Value = strName Then
Sheets("Receipt_Download").Select
Range("A" & i & ":IV" & i).Copy
Sheets("Summary").Select
Range("A" & lngPasteRow & ":IV" & lngPasteRow).Select
ActiveSheet.Paste
lngPasteRow = lngPasteRow + 1
End If
Next i
j = j + 1
Sheets("Receipt_Download").Select
Rows("1:1").Select
Selection.Copy
Sheets("Summary").Select
Rows("1:1").Select
ActiveSheet.Paste
Columns("D:E").Select
Selection.NumberFormat = "m/d/yyyy"
Sheets("Summary").Select
Range("B25000").Select
ActiveCell.FormulaR1C1 = "Grand Total"
Range("B25000").Select
Selection.Font.Bold = True
Columns("G:G").Select
Selection.Insert Shift:=xlToRight
Range("G1").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-2]=0,""0"",RC[-1])"
Range("G1").Select
Selection.AutoFill Destination:=Range("G1:G24950")
Range("G25000").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-24950]C:R[-1]C)"
Range("G25000").Select
Selection.Copy
Range("F25000").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("G:G").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Sheets("Summary").Select
Range("F25000").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Names").Select
With Columns("B")
.Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
ActiveSheet.Paste
Sheets("Summary").Select
Range("b1:b30000").Select
For Each Cell In Selection
If Cell.Value = "" Then
Cell.ClearContents
End If
Next Cell
Range("b1:b30000").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Sheets("Summary").Select
Range("D2").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Names").Select
***With Columns("C")
.Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate***
End With
ActiveSheet.Paste
Sheets("Summary").Select
Range("A1:Z5000").Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Range("A1").Select
Application.CutCopyMode = False
Selection.Copy
Application.CutCopyMode = False
File = "C:\Documents and Settings\user\Desktop\New FBO\" & strName & "\" & strName & " Receipts.xls"
ActiveWorkbook.SaveAs Filename:=File, _
FileFormat:=xlNormal, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
ActiveWorkbook.Close
IngPasteRow = IngPasteRow + 1
Sheets("Summary").Select
Selection.ClearContents
Next c
End Sub
I would really appreciate any help, I am certainly no VBA master and this has been quite troublesome.
Replace this part of your code
Sheets("Summary").Select
Range("D2").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Names").Select
With Columns("C")
.Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
ActiveSheet.Paste
with
Dim lRow As Long
With Sheets("Names")
lRow = .Range("C" & .Rows.Count).End(xlUp).Row + 1
Sheets("Summary").Range("D2").Copy .Range("C" & lRow)
End With
Now try it.
Also few tips
Avoid .Select and .Activate They are a major cause of errors
Indent and appropriately comment your code. Your code is very difficult to read. If you don't indent/comment your code, you will realize that you will not recognize your OWN code if you visit it say after a week :)
In support of Siddharth's answer above, I have take a portion of your code (up to where your break happens) and have indented and avoided the .Select and .Activate that he mentions. Hopefully this gives you a good start on how to make your code more readable for debugging and understanding.
For Each c In rng
For i = 2 To lngLastRow
strName = c.Value
If Sheets("Receipt_Download").Range("J" & i).Value = strName Then
Sheets("Receipt_Download").Range("A" & i & ":IV" & i).Copy _
Destination:=Sheets("Summary").Range("A" & lngPasteRow & ":IV" & lngPasteRow)
lngPasteRow = lngPasteRow + 1
End If
Next i
j = j + 1
Sheets("Receipt_Download").Rows("1:1").Copy Destination:=Sheets("Summary").Rows("1:1")
With Sheets("Summary")
.Columns("D:E").NumberFormat = "m/d/yyyy"
With .Range("B25000")
.Formula = "Grand Total"
.Font.Bold = True
End With
.Columns("G:G").Insert Shift:=xlToRight
With Range("G1")
.FormulaR1C1 = "=IF(RC[-2]=0,""0"",RC[-1])"
.AutoFill Destination:=Range("G1:G24950")
End With
With ("G25000")
.FormulaR1C1 = "=SUM(R[-24950]C:R[-1]C)"
.Copy
End With
.Range("F25000").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.Columns("G:G").Delete Shift:=xlToLeft
.Range("F25000").Copy Destination:=Sheets("Names").Columns("B").Find(what:="", after:=Sheets("Names").Cells(1, 1), LookIn:=xlValues)
End With