How to get back formula after applied vlookup using vba? - vba

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:

Related

Vba search and paste solution

i would like to come up with vba sub that searching value from one specified cell (job) across all sheets and then pastes rows but only with selected columns. If value not found any error message instead paste value.
I know it's bigger project but I'm fresh so try to my best.
As far i have solution for whole rows:
Sub TEST()
Dim tws As String
Dim l_row As String
Dim l_rowR As String
Dim job As String
Dim i As Integer
Set tws = ThisWorkbook.Sheets("Data")
tws.Range("A20") = "STATS:"
job = tws.Range("B5")
lastRow = Worksheets("Sheet1").Range("E" & Rows.Count).End(xlUp).Row
lastRowRpt = tws.Range("A" & Rows.Count).End(xlUp).Row
For i = 3 To lastRow
If Worksheets("Sheet1").Range("E" & i).Value = job And _
Worksheets("Sheet1").Range("D" & i).Value = "x2" Then
Worksheets("Sheet1").Rows(i).Copy
lastRowRpt = tws.Range("A" & Rows.Count).End(xlUp).Row
tws.Range("A" & lastRowRpt + 1).Select
tws.Paste
End If
Next i
End Sub

Data Extraction over multiple worksheets

I'm totally new to VBA and I'm trying to script an excel module to extract a specific section on each sheet of a workbook and format them and output together to 1 sheet on a new workbook.
So far I have this;
Public Sub extractCol()
' Find FF&E Section, Add 3 rows and Identify relevant columns.
Dim rFind As Range
With Range("A:A")
Set rFind = .Find(What:="FF&E", LookAt:=xlWhole, MatchCase:=False,
SearchFormat:=False)
If Not rFind Is Nothing Then
NumRange = rFind.Row + 3 ' Find FF&E line and add three
CRange = "C" & NumRange & ":" & "C" & NumRange + 100 ' Define First 100
Lines in Column C
ERange = "E" & NumRange & ":" & "E" & NumRange + 100 ' Define First 100
Lines in Column E
KRange = "K" & NumRange & ":" & "K" & NumRange + 100 ' Define First 100
Lines in Column K
MRange = "M" & NumRange & ":" & "M" & NumRange + 100 ' Define First 100
Lines in Column M
Set range1 = Union(Range(CRange), Range(ERange), Range(KRange),
Range(MRange)) ' Combine individual column ranges in to one selection
range1.Copy ' Copy new combined range
Set NewBook = Workbooks.Add ' Open new Workbook
ActiveCell.PasteSpecial Paste:=xlPasteValues ' Paste to new Workbook
End If
End With
End Sub
This is great as it extracts the bits that I wan't correctly but it only does the current sheet. How do I loop this to do all sheets?
Secondly I would like to paste all the results to the same sheet under one another?
And finally I have the below script that extracts the sheet name and formats it. Ideally I would like to add a column to the output above which would display this data depending on which sheet it came from.
Function FindRoom()
shtName = ActiveSheet.Name
Dim arr() As String
arr = VBA.Split(shtName, " ")
xCount = UBound(arr)
If xCount < 1 Then
FindRoom = ""
Else
FindRoom = arr(xCount)
End If
End Function
Sorry, I know this is not a simple one answer question but any help would be grateful even if it's just pointing me in the right direction.
Try this. I've added a worksheet variable ws. This puts the sheet name in column A of the new workbook, and the data in col B onwards. I have also added declarations for all the variables.
Public Sub extractCol()
'Find FF&E Section, Add 3 rows and Identify relevant columns.
Dim rFind As Range, CRange As String, ERange As String, KRange As String, MRange As String
Dim ws As Worksheet
Dim NewBook As Workbook
Dim NumRange As Long
Set NewBook = Workbooks.Add ' Open new Workbook
For Each ws In ThisWorkbook.Worksheets
With ws
Set rFind = .Range("A:A").Find(What:="FF&E", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
NumRange = rFind.Row + 3 ' Find FF&E line and add three
CRange = "C" & NumRange & ":" & "C" & NumRange + 100 ' Define First 100 Lines in Column C
ERange = "E" & NumRange & ":" & "E" & NumRange + 100 ' Define First 100 Lines in Column E
KRange = "K" & NumRange & ":" & "K" & NumRange + 100 ' Define First 100 Lines in Column K
MRange = "M" & NumRange & ":" & "M" & NumRange + 100 ' Define First 100 Lines in Column M
Set range1 = Union(.Range(CRange), .Range(ERange), .Range(KRange), .Range(MRange)) ' Combine individual column ranges in to one selection
range1.Copy ' Copy new combined range
NewBook.Sheets(1).Range("B" & Rows.Count).End(xlUp)(2).PasteSpecial Paste:=xlPasteValues ' Paste to new Workbook
NewBook.Sheets(1).Range("A" & Rows.Count).End(xlUp)(2).Resize(range1.Rows.Count).Value = FindRoom(ws)
End If
End With
Next ws
End Sub
Function FindRoom(ws As Worksheet)
shtName = ws.Name
Dim arr() As String
arr = VBA.Split(shtName, " ")
xCount = UBound(arr)
If xCount < 1 Then
FindRoom = ""
Else
FindRoom = arr(xCount)
End If
End Function

VBA Script Code for reading a xls and manipulating cells

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

Need to transpose rows while transferring data from one excel sheet to another

My original question was posted here.
Basically I needed some help transferring data from one sheet to another based on values in the first sheet. I am using a modified bit of code provided by user keong kenshih.
I added an additional check against another row to the IF statement, and I have this for my code:
Option Explicit
Dim MyWorkbook As Workbook
Dim MyWorksheet As Worksheet
Dim MyOutputWorksheet As Worksheet
So I need to output only certain columns. Also I need them to import to certain rows and columns on the second sheet, the CONTRACT sheet. Column A on the MAIN sheet goes to column A starting at row 17 on the CONTRACT sheet. B to B , E to D, F to E, all starting at row 17 on the CONTRACT sheet.
Rows 17-42 on the CONTRACT sheet will contain data.
Sub PullData()
Set MyWorkbook = Workbooks(ActiveWorkbook.Name)
Set MyWorksheet = MyWorkbook.Sheets("MAIN")
Set MyOutputWorksheet = MyWorkbook.Sheets("CONTRACT")
Dim myValue As Long
Dim RowPointer As Long
For RowPointer = 6 To MyWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
If MyWorksheet.Range("A" & RowPointer).V alue > 0 And
MyWorksheet.Range("A" & RowPointer).Value <> ""
MyWorksheet.Range("F" & RowPointer).Value > 0 And
MyWorksheet.Range("F" & RowPointer).Value <> ""Then
If MyOutputWorksheet.Cells(Rows.Count, "B").End(xlUp).Row > 15
Then
Exit Sub
End If
MyWorksheet.Range(("A" & RowPointer) & ":C" & RowPointer).Copy
Destination:=MyOutputWorksheet.Range("A" &
MyOutputWorksheet.Cells(Rows.Count, "B").End(xlUp).Row + 1)
End If
Next RowPointer
End Sub
Give this a try :
Sub PullData()
Dim wRow As Long, _
RowPointer As Long, _
MyWorkbook As Workbook, _
Ws As Worksheet, _
OutWs As Worksheet
Set MyWorkbook = Workbooks(ActiveWorkbook.Name)
Set Ws = MyWorkbook.Sheets("MAIN")
Set OutWs = MyWorkbook.Sheets("CONTRACT")
With Ws
For RowPointer = 6 To .Cells(.Rows.Count, "B").End(xlUp).Row
If .Range("A" & RowPointer).Value > 0 And _
.Range("A" & RowPointer).Value <> "" And _
.Range("F" & RowPointer).Value > 0 And _
.Range("F" & RowPointer).Value <> "" Then
'This line would get you out of the loop after the first copy because _
'You first paste on line 17 and then the below left part will be equal to 18
'If OutWs.Cells(OutWs.Rows.Count, "B").End(xlUp).Row > 15 Then Exit Sub
wRow = OutWs.Rows(OutWs.Rows.Count).End(xlUp).Row + 1
'Always start copy after (or at) line 17
If wRow <= 17 Then wRow = 17
'More efficient way to copy data between ranges
OutWs.Range("A" & wRow).Value = Ws.Range("A" & RowPointer)
OutWs.Range("B" & wRow).Value = Ws.Range("B" & RowPointer)
OutWs.Range("D" & wRow).Value = Ws.Range("E" & RowPointer)
OutWs.Range("E" & wRow).Value = Ws.Range("F" & RowPointer)
End If
Next RowPointer
End With
Set MyWorkbook = Nothing
Set Ws = Nothing
Set OutWs = Nothing
End Sub

Copy a variable range from other files to a summary sheet

This code is to open files and go to a certain sheet, grab everything from A11 to AC(down), go back to a report and progressively paste it one after the other, which works with the exception that it can't find the next available row so it pastes the new data over the previous data. I am quite sure that my efforts with LastRowSrce and LastRowDest is the culprit but I can't get it right. I saw some posts with UsedRange so I tried that but couldn't get it right either.
Any help greatly appreciated.
Sub CSReport()
Dim y As Long
Dim Wkb As Workbook
Dim Wks As Worksheet
Dim SFile As String 'srce file
Dim GWB As String 'dest file
Dim R1 As Range
Dim R2 As Range
Dim LastRowSrce As Long 'find last row in srce file
Dim LastRowDest As Long 'find last row in dest file
Set Wkb = thisWorkBook
Set Wks = Wkb.Worksheets("CS Report")
Wks.Range("A11:AD10000").ClearContents
Wks.Range("A4").value = "Status at " & Time & " " & Format(Date, "Long date")
y = 11 'start row
SFile = Wkb.Path & "\"
GWB = Dir(SFile & "*Audit*")
Do While Len(GWB) > 0
workbooks.Open fileName:=SFile & GWB
LastRowSrce = workbooks(GWB).Worksheets("Audit Plan").Cells(Rows.Count, "A").End(xlUp).Row
LastRowDest = Wks.Cells(Rows.Count, "A").End(xlUp).Row + 1
Set R1 = workbooks(GWB).Worksheets("Audit Plan").Range("A" & y & ":AB" & LastRowSrce)
Set R2 = Wks.Range("A" & y & ":AB" & LastRowSrce)
R2.value = R1.value
workbooks(GWB).Close False
y = y + 1
GWB = Dir
Loop
Wkb.Save
End Sub
Set R2 = Wks.Range("A" & y & ":AB" & LastRowSrce)
you keep setting the same range on the destination sheet... you need it to be dynamic.
set R2 = Wks.Range("A" & LastRowDest & ":AB" & LastRowDest+LastRowSrce-11)
try that...