I have an excel sheet with just one worksheet. The first row of this excel sheet has the Title for the columns.
The worksheet has data in below columns and n number of rows:
Columns: A | B | C | D | E | F | G | H
First I am creating a copy of the file and renaming it - This WORKS!
'Copy and rename the file
Dim sourceFile As String, destFile As String
sourcePath = Range("D6")
destFile = Split(sourcePath, ".")(0) + "_Formated.xls"
FileCopy sourcePath, destFile
I want to read this destFile excel sheet via VBA code. I will doing some cell manipulation so please give me a working code to understand how that whole worksheet is read and how I can access a particular row while in a for loop.
I also want to know the code to add new column title and values to this destFile excel sheet via VBA code.
Whats the code for just clearing the cell value via VBA code and not delete the cell.
I want to read this destFile excel sheet via VBA code. I will doing some cell manipulation so please give me a working code to understand how that whole worksheet is read and how I can access a particular row while in a for loop.
dim sh as Worksheet
set sh = Workbooks.Open(destFile).Worksheets(1)
I also want to know the code to add new column title and values to this destFile excel sheet via VBA code.
sh.rows(1).Insert Shift := xlDown
ThisWorkbook.Worksheets(1).Rows(1).Copy sh.Rows(1)
Whats the code for just clearing the cell value via VBA code and not delete the cell.
sh.Range("A1").Value = ""
I managed to get this done with the below code.
This is the worst way to code it and does not look anything sophisticated but it gets the job done.
Thanks!
Sub Format()
'Copy and rename the file
Dim SourceFile As String, DestFile As String
SourceFile = Range("D6")
SourceString = Range("D3")
TestSuiteName = Range("D2") & "\"
DestFile = Split(SourceFile, ".")(0) + "_Formated.xls"
On Error GoTo ErrorHandler:
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FileExists(DestFile) Then
FileCopy SourceFile, DestFile
End If
'Read DestFile worksheet content
Dim wks As Worksheet
Set wks = Workbooks.Open(DestFile).Worksheets(1)
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long
LastRow = wks.Cells(wks.rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
If Cells(i, 6).Value = "Step 1" Then
Cells(i, 7) = "Other_Migration_Fields" & Cells(i, 7) & vbLf & vbLf & "QC Path:" & Cells(i, 8)
Cells(i, 8) = Replace(Cells(i, 8), SourceString, TestSuiteName)
Else
Cells(i, 1) = ""
Cells(i, 2) = ""
Cells(i, 7) = ""
Cells(i, 8) = ""
End If
Next i
ErrorHandler:
Msg = "Error # " & Str(Err.Number) & " was generated by " & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
If Err.Number <> 0 Then
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
Else
MsgBox "Success!"
End If
Exit Sub
End Sub
Related
I have two workbooks:
Planner
Column K Column AG
123 £100
246 £20
555 £80
Master
Column D Column R
123 £100
246 £20
555 £80
I am trying to copy the values from Planner, Column AG into Column R (Master) where my item numbers in Column D (Master) match with column K (Planner).
My code below produces no error and it is not producing any results - despite their being several matches.
Please can someone show me where i am going wrong?
For the avoidance of doubt, my workbook is definitely opening ok so is finding the file.
Code:
Sub PlannerOpen()
'Set Variables
Dim wb2 As Workbook
Dim i As Long
Dim j As Long
Dim lastRow As Long
Dim app As New Excel.Application
'Find Planner
If Len(FindDepotMemo) Then
'If Found Then Set Planner Reference.
app.Visible = False 'Visible is False by default, so this isn't necessary
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.EnableEvents = False
Set wb2 = Workbooks.Open(FindDepotMemo, ReadOnly:=True, UpdateLinks:=False)
'If We have our planner lets continue...
'With my workbook
With wb2.Worksheets(1)
lastRow = .Cells(.Rows.Count, "K").End(xlUp).Row
'Lets begin our data merge
j = 2
For i = 2 To lastRow
'If data meets criteria
'Check Planner For Turnover
If ThisWorkbook.Worksheets("Data").Range("D" & j).Value = .Range("K" & i).Value Then ' check if Item number matches
ThisWorkbook.Worksheets("Data").Range("R" & j).Value = .Range("AG" & i).Value
j = j + 1
End If
'Continue until all results found
Next i
End With
'All Done, Let's tidy up
'Close Workbooks
'wb2.Close SaveChanges:=False
'app.Quit
'Set app = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
End If
End Sub
Function FindDepotMemo() As String
Dim Path As String
Dim FindFirstFile As String
Path = "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\" & "8." & " " & Year(Date) & "\"
FindFirstFile = Dir$(Path & "*.xlsx")
While (FindFirstFile <> "")
If InStr(FindFirstFile, "Planner") > 0 Then
FindDepotMemo = Path & FindFirstFile
Exit Function
End If
FindFirstFile = Dir
Wend
End Function
Instead of having 2 For loops, just use the Application.Match to find matches between values in your 2 workbooks.
Use this code section below to replace with yours:
With wb2.Worksheets(1)
Dim MatchRow As Variant '<-- define variable to get the row number if Match is successful
lastRow = .Cells(.Rows.Count, "K").End(xlUp).Row
'Lets begin our data merge
For i = 2 To lastRow
' If data meets criteria
' Check Planner For Turnover
' Use Application.Match to find matching results between workbooks
If Not IsError(Application.Match(ThisWorkbook.Worksheets("Data").Range("D" & i).Value, .Range("K2:K" & lastorw), 0)) Then ' check if Match is successful
MatchRow = Application.Match(ThisWorkbook.Worksheets("Data").Range("D" & i).Value, .Range("K2:K" & lastorw), 0) ' <-- get the row number where the match was found
ThisWorkbook.Worksheets("Data").Range("R" & j).Value = .Range("AG" & MatchRow).Value
End If
'Continue until all results found
Next i
End With
you could refactor your code as follows:
Option Explicit
Sub PlannerOpen()
Dim dataRng As Range, cell As Range
Dim depotMemo As String
Dim iRow As Variant
If FindDepotMemo(depotMemo) Then '<--| if successfully found the wanted file
With ThisWorkbook.Worksheets("Data1") '<--| reference your "Master" workbook relevant worksheet
Set dataRng = .Range("D2", .Cells(.Rows.Count, "D").End(xlUp)) '<--| set its item numbers range
End With
With Workbooks.Open(depotMemo, ReadOnly:=True, UpdateLinks:=False).Worksheets(1) '<--| open depotMemo workbook and reference its first worksheet
For Each cell In .Range("K2", .Cells(.Rows.Count, "K").End(xlUp)) '<--| loop through referenced worksheet column "K" cells from row 2 down to last not empty one
iRow = Application.Match(cell.Value, dataRng, 0) '<--| try finding current depotMemo item number in Master item numbers range
If Not IsError(iRow) Then dataRng(iRow, 1).Offset(, 14).Value = cell.Offset(, 22) '<--| if found then grab depotMemo current item amount and place it in corresponding "master" data sheet column R
Next
.Parent.Close False
End With
End If
End Sub
Function FindDepotMemo(depotMemo As String) As Boolean
Dim Path As String
Dim FindFirstFile As String
Path = "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\" & "8." & " " & Year(Date) & "\"
FindFirstFile = Dir$(Path & "*.xlsx")
While (FindFirstFile <> "")
If InStr(FindFirstFile, "Planner") > 0 Then
FindDepotMemo = True
depotMemo = Path & FindFirstFile
Exit Function
End If
FindFirstFile = Dir
Wend
End Function
I am relatively new to VBA.
I have a target workbook where the first step is somebody has to write something. If not an error message pops up.
After they filled in their data the code will ask them to open the source workbook(they downloaded the file before). From the source workbook certain columns are read. This all works fine in the code. The problem I have is to get what they filled in the target workbook to be copied down in column (A4:A(last row in source workbook). So the length until where their manually entered data has to be copied down has to be equal to the length of data in the source workbook.
Sub get_rate_codes()
Dim CheckCell As Range
Dim wb_source As Workbook
Dim wb_target As Workbook
Dim strPathName As String
Dim lastRow As Long
For Each CheckCell In Sheets("rate_codes").Range("F3").Cells
If Len(Trim(CheckCell.Value)) = 0 Then
CheckCell.Select
MsgBox "Cell " & CheckCell.Address(0, 0) & " is empty. Please enter SITA."
Exit Sub
End If
Next CheckCell
'start to open file
Application.ScreenUpdating = False
'start is the starting cell while lastRow measures the last data row in the external file
Start = 4
'continue to copy data from the rate codes report
Set wb_target = ActiveWorkbook
With wb_target.Sheets("rate_codes")
lastRow = wb_source.UsedRange.SpecialCells(xlCellTypeLastCell).Row
strPathName = Application.GetOpenFilename()
If strPathName = "False" Then
Exit Sub
End If
Set wb_source = Workbooks.Open(strPathName, 0)
.Range("B" & Start & ":B1000").Value = wb_source.Sheets(1).Range("E2:E1000").Value
.Range("C" & Start & ":C1000").Value = wb_source.Sheets(1).Range("H2:H1000").Value
.Range("D" & Start & ":D1000").Value = wb_source.Sheets(1).Range("G2:G1000").Value
.Range("E" & Start & ":E1000").Value = wb_source.Sheets(1).Range("K2:K1000").Value
.Range("A" & Start & ":A" & lastRow).Value = wb_target.Sheets(2).Range("F2").Value '
wb_source.Close (False)
End With
'close file without saving
Application.ScreenUpdating = True
End Sub
To find the last row you can do this.
Dim lastRow As Long
lastRow = wb_source.Cells(wb_source.Rows.count, "A").End(xlUp).Row
Then you can write to the next line.
.Range("A" & lastRow + 1).Value =
I'm using loop statements to find the text " Measured Values" in a cell in column "B" and store it's cell location. From this cell location I then want to continue down the "B" column to find each cell that contains the text " 4Wire" and at the same time read the same row but "I" column cell contents and write it to a master .csv file. I want to stop parsing the file upon finding the cell in column "B" that contains the text " First Article Verification". My two Do/While loops are not executing as I do not know if the Cells(i, "B").Value is used correctly. Any ideas as to the problem? Thanks in advance.
Sub ImportKeyDataFromCSVsCOPY()
'Summary: Import specific data from all CSV files from a folder into a single sheet
Dim wbCSV As Workbook
Dim wsMstr As Worksheet
Dim fPath As String
Dim fCSV As String
Dim NR As Long
Dim fPathDone As String
Dim Count As Long
Dim i As Long
Dim k As Long
Dim d As String
Dim MVnotFound As Boolean
Dim Cells As String
fPath = "F:\i9 Tester\VB Macro spreadsheet\" 'path to CSV files, include the final \ in this string
fPathDone = fPath & "Imported\" 'remember final \ in this string
On Error Resume Next
MkDir fPathDone 'creates the completed folder if missing
On Error GoTo 0
Set wsMstr = ThisWorkbook.Sheets("MasterCSV") 'sheet in thisworkbook to collate data into
NR = wsMstr.Range("A" & Rows.Count).End(xlUp).Row + 1 'next empty row to add
Count = 1 'Initialize count to 1
Application.ScreenUpdating = False 'speed up macro
fCSV = Dir(fPath & "*.csv") 'start the CSV file listing
Do While Len(fCSV) > 0
i = 0
MVnotFound = True
Set wbCSV = Workbooks.Open(fPath & fCSV) 'open a CSV file
Do While MVnotFound 'loop to find " Measured Values" text i = i + 1
If Cells(i, "B").Value = " Measured Value" Then
MVnotFound = False
End If
Loop
Do
If Cells(i, "B").Value = " 4Wire" Then
wsMstr.Range("H" & NR).Value = Cells(i, "I").Value
ElseIf Cells(i, "B").Value = " Fist Article Verification" Then
d = " First Article Verification"
End If
i = i + 1
Loop While d <> " First Article Verification"
wbCSV.Close False 'close the opened CSV
NR = NR + 1 'increment next target row
Name fPath & fCSV As fPathDone & fCSV 'move file to IMPORTED folder
fCSV = Dir 'ready next CSV filename
Loop
Application.ScreenUpdating = True
End Sub
I don't think Cells(i,"B") is a valid argument. i cannot be zero (try starting at i+1) and the column cannot be a letter. For example use Cells(1,2) to refer to B1 (Column 2 Row 1)
I have vba script which apply vlookup from one excel file another file. Its work fine but the output excel file only contains output data but i need formula for that vlookup output because i need apply same thing next by using copy paste so i need a help to get formula also in output excel. This my vba script
Sub vloo()
Dim rng As Range
Dim user As String
Dim file As String
Dim n As Integer
Dim m As Integer
Dim c As Integer
Dim a As Variant
n = 1
m = 0
c = 2
file = "E:\output8.xls"
Workbooks.Add
ActiveWorkbook.SaveAs file
Set nb = Application.Workbooks.Open(file)
Set ns = nb.Worksheets("Sheet1")
'get workbook path
filename = Application.GetOpenFilename(FileFilter:="Excel Files (*.xlsx), *.xls", Title:="Please select a file")
'set our workbook and open it
Set wb = Application.Workbooks.Open(filename)
'set our worksheet
Set ws = wb.Worksheets("Sheet1")
'set the range for vlookup
Set rng = ws.Range("F:AI")
For y = 6 To 20
m = m + 1
user = MsgBox(ws.Cells(1, y), 4, "You Want This")
If user = 6 Then
ns.Cells(1, n) = ws.Cells(1, y)
ns.Cells(1, n).Interior.Color = vbYellow
n = n + 1
If m > 1 Then
ns.Cells(2, c).Value = Application.VLookup(ns.Cells(2, 2).Value, rng, m, False)
c = c + 1
End If
End If
Next
End Sub
After execute this script and went to output excel ns and press F2 in each entry but getting only data dont know why formula are not there so i need formula also.
Simply alter your script so that it writes the formula rather than the evaluation thereof:
Change this:
ns.Cells(2, c).Value = Application.VLookup(ns.Cells(2, 2).Value, rng, m, False)
To this (revised to fully qualify the range used in the VLookup's third argument):
ns.Cells(2, c).Formula = "=VLookup(" _
& ns.Cells(2, 2).Value & "," _
& "[" & rng.Parent.Parent.Name & "]'" & rng.Parent.Name & "'!" & rng.Address & "," _
& m & "," _
& "False)"
If you debug, assuming I did not make any typos, then the that should have the third argument like so:
[Mains_heet_for_SEA_October14.xlsx]'Sheet1'!$F$2:$M$2
Note this may slow down the macro since formulas may re-evaluate during runtime. There are ways around this using the Application.Calculation property if that becomes an issue.
UPDATE
You can verify this works in principle with a Debug statement. Put it in it's own procedure if you'd like, and test it out like so:
Sub foo()
Dim rng As Range
Dim m As Integer
m = 3
Set rng = Range("A1:D10")
Debug.Print "=VLookup(" _
& "some_value" & "," _
& "[" & rng.Parent.Parent.Name & "]'" & rng.Parent.Name & "'!" & rng.Address & "," _
& m & "," _
& "False)"
End Sub
Here is proof that this works:
Is there a way to get the contents of a text file and add it to the clip board?
I am thinking along the lines of setting the contents of the DataObject as the contents from a file and then adding the DataObject to the clipboard.
Is this something you can do from Excel VBA?
This is the Code I am using to get the data into a txt file in the correct format. However, I also require it in the clipboard so I can just paste it.
With ws2
Open "C:\Users\peter.carr\Documents\New Action Plan\copytest.txt" For Append As #1
lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
For i = lastrow To 2 Step -1
str1 = ""
Print #1, ws2.Cells(i, 1).Value & ") " & ws2.Cells(i, 2).Value
Print #1,
For Each cell In .Range(.Cells(i, 6), .Cells(i, lastcol))
g = i - 1
If cell.Column <> 4 And cell.Column <> 5 And cell.Value <> "" And cell.Value <> "NEW ACTION" Then
Print #1, cell.Value
Print #1, "(" & cell.Offset(-g, 0).Value & ")"
Print #1,
End If
Next cell
Next i
Close #1
End With
I know I could just open the file and copy it. However, the idea is that this is part of a larger process to automate things, hence I really want to be able to fo this without opening the file.
Sub TextToClipboard()
Dim sFile As String: sFile = "C:\Test.txt"
Dim sText As String
Dim Dataobj As DataObject
Set Dataobj = New DataObject
Open sFile For Input As #1
sText = Input(LOF(1), 1)
Dataobj.SetText sText
Dataobj.PutInClipboard
End Sub