a kind soul made me this code for another question i asked. But im thinking about text recognition. So i got a data input in sheet1, there is some headers for each column in the data input, and i want to sort by specific header names, copy them, and paste the two rows of the columns which header matches my keywords, in sheet2. Pasting the data in sheet2, should be at the first two lines available, like here in my code already. Really want to keep most of the code as possible and then maybe only change the sub where i copy the two rows in a specific range. Would appreciate the help:)
Option Explicit
Sub call_copy_sub_ranges()
Dim ws1 As Worksheet, wsOut As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Ark1")
Set wsOut = ThisWorkbook.Worksheets("Ark2")
Dim ar
ar = Array("HeaderA", "HeaderB", "HeaderC", "HeaderD", "HeaderE", _
"HeaderF", "HeaderG", "HeaderH", "HeaderI", "HeaderJ", "HeaderK", _
"HeaderL", "HeaderM", "HeaderN", "HeaderO", "HeaderP", "HeaderQ", _
"HeaderR", "HeaderS", "HeaderT", "HeaderU", "HeaderV", "HeaderW", _
"HeaderX", "HeaderY", "HeaderZ", "HeaderAA", "HeaderAB", "HeaderAC", _
"HeaderAD", "HeaderAE", "HeaderAF", "HeaderAG", "HeaderAH", "HeaderAI", _
"HeaderAJ", "HeaderAK", "HeaderAL", "HeaderAM", "HeaderAN", "HeaderAO", _
"HeaderAP", "HeaderAQ", "HeaderAR", "HeaderAS", "HeaderAT", "HeaderAU", _
"HeaderAV", "HeaderAW", "HeaderAX", "HeaderAY")
wsOut.Range("A1:AY1").Value = ar
copy_sub_ranges ws1, wsOut
MsgBox "Done"
End Sub
Sub copy_sub_ranges(ByVal ws1 As Worksheet, ByVal wsOut As Worksheet)
Dim rng As Range, rngOut As Range, ar, s
ar = Array("S2:S3", "BF7:BH8", "BI9:CC10", _
"CD9:CQ9", "CR9:CS10", "CT9:CV9", "CW9:CW10", "CX10", "EE9:EI10")
' target
Set rngOut = wsOut.Cells(wsOut.Rows.Count, 1).End(xlUp)
If Not IsEmpty(wsOut.Range("A1").Text) Then
Set rngOut = rngOut.offset(1, 0)
End If
For Each s In ar
Set rng = ws1.Range(s)
Debug.Print rng.Address, rngOut.Address
rng.Copy rngOut
Set rngOut = rngOut.offset(0, rng.Columns.Count)
Next
' underline
Set rng = wsOut.Cells(wsOut.Rows.Count, 1).End(xlUp)
With rng.Resize(1, rngOut.Column - 1).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlMedium
End With
End Sub
You could execute an SQL statement on your worksheet, or on a range within the worksheet. This would allow you to trivially select only specific columns, and sort by specific columns.
Add a reference (Tools -> References...) to Microsoft ActiveX Data Objects; choose the latest version (usually 6.1).
Then you could write code similar to the following:
Dim sql As String
sql = _
"SELECT HeaderA, HeaderG, HeaderP " & _
"FROM [Sheet1$] " & _
"ORDER BY HeaderQ, HeaderR"
' If your data is only in a specific range, you can limit to that range:
'sql = _
' "SELECT HeaderA, HeaderG, HeaderP " & _
' "FROM [Sheet1$B5:AA17] " & _
' "ORDER BY HeaderQ, HeaderR"
Const filepath As String = "C:\path\to\excel\file.xlsx"
Dim connectionString As String
connectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=""" & filepath & """;" & _
"Extended Properties=""Excel 12.0;HDR=Yes"""
Dim rs As New ADODB.Recordset
rs.Open sql, connectionString
ThisWorkbook.Worksheets("Ark2").Range("A1").CopyFromRecordset rs
Note that there's nothing preventing you from using an array of strings as the selected columns, or as the sort fields; use the Join function to combine the field names into a comma-separated string:
Dim fieldnames() As String
fieldnames = Array("HeaderB", "HeaderC", "HeaderD")
Dim sortnames() As String
sortnames = Array("HeaderM", "HeaderN", "HeaderO")
sql = _
"SELECT " & Join(fieldnames, ", ") & " " & _
"FROM [Sheet1$] " & _
"ORDER BY " & Join(sortnames, ", ")
fieldnames and sortnames could be populated from different cells:
Dim sheet As Worksheet
Set sheet = Worksheets("Sheet1")
fieldnames = Array(sheet.Range("A1").Value, sheet.Range("B1").Value))
Related
I have certain ranges within an Excel file and I create an instance of Word template from within Excel VBA. This Word template has a bunch of Doc variables so that I can replace the values of those Doc Variables with my defined variables using precise Excel sheet ranges. For some weird reason, Doc variable laid down in Word template file are not being updated.
Could someone please extend your help and advise what possible mistake I might be making here.
Sub Generate_CoverLetter()
Dim client, bo, invoice_currency, vesselName As String
Dim invoiceAmount 'As Single
Dim bo_rng, rngBO, rngCustName, rngAmount, rngVesselName, rngCurrencyCode, rngCommencedDate As Range
Dim SearchParams As Variant
Dim SearchParamsCols As Variant
Dim wdApp As Object
Dim wdDoc As Word.Document
Set bo_rng = Application.InputBox( _
Title:="Select BO range", _
Prompt:="Select a cell to pull in BO number....", _
Type:=8)
bo = bo_rng.value
lastRow = Range("A" & Application.Rows.Count).End(xlUp).Row
SearchParams = Array("field_19", "customer_name", "total_amount", "invoice_currency_code", "field_43", "field_71")
orderColumn = seachParamColumn(SearchParams(0))
cnameColumn = seachParamColumn(SearchParams(1))
amountColumn = seachParamColumn(SearchParams(2))
currencyColumn = seachParamColumn(SearchParams(3))
commencedDateColumn = seachParamColumn(SearchParams(4))
vesselColumn = seachParamColumn(SearchParams(5))
' core ranges
Set rngBO = Range(Cells(2, orderColumn), Cells(lastRow, orderColumn))
Set rngCustName = Range(Cells(2, cnameColumn), Cells(lastRow, cnameColumn))
Set rngAmount = Range(Cells(2, amountColumn), Cells(lastRow, amountColumn))
Set rngVesselName = Range(Cells(2, vesselColumn), Cells(lastRow, vesselColumn))
' invoice parameter ranges
Set rngCurrencyCode = Cells(bo_rng.Row, currencyColumn)
Set rngCommencedDate = Cells(bo_rng.Row, commencedDateColumn)
client = Cells(bo_rng.Row, rngCustName.Column)
InvoiceNumber = Cells(bo_rng.Row, 1) ' .value
invoice_currency = rngCurrencyCode.value
invoiceAmount = Application.WorksheetFunction.SumIfs(rngAmount, rngBO, "=" & bo, rngCustName, "=" & client)
invoiceAmount = Format(invoiceAmount, "#,##0.00")
commencedDate = rngCommencedDate.value
' This weird looking loop is here because an order might have several rows in Excel data
' but only one of those rows might have the name of the vessel
For Each cell In rngVesselName.SpecialCells(xlCellTypeVisible)
If cell.Column = vesselColumn And Not IsEmpty(cell) Then
vesselName = cell.value
Exit For
End If
Next
MsgBox InvoiceNumber & vbLf & _
invoice_currency & " " & invoiceAmount & vbLf & _
client & vbLf & _
vesselName & vbLf & _
commencedDate
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
Set wdDoc = wdApp.Documents.Add
Set wdDoc = wdApp.Documents.Open("C:\Users\smiq\Documents\Custom Office Templates\CL.dotm")
Set wdDoc = ActiveDocument
wdDoc.Activate
wdApp.WindowState = wdWindowStateMaximize
ActiveDocument.Variables("wd_vesselName").value = vesselName
ActiveDocument.Variables("wd_CommencedDate").value = commencedDate
ActiveDocument.Variables("wd_invoiceNumber").value = InvoiceNumber
ActiveDocument.Variables("wd_invoiceAmount").value = invoiceAmount
End Sub
Function seachParamColumn(param As Variant)
Dim c
With Range("1:1")
Set c = .Find(param, , xlValues)
If Not c Is Nothing Then
seachParamColumn = Range(c.Address).Column
End If
End With
End Function
I am using a userform to update existing data on a worksheet. I can
create new records just fine. I created an update userform with a
combobox to search for the names. It pulls the persons data just fine and I am able to change the information. But when I go to click the update button, an error occurs. Before it was adding a totally new line which I did not want to happen so I adjusted my code. I just want to update an existing line of data with the edited information.
I have tried to use the MATCH function in VBA after it was replicating records.
Private Sub Update_record_Click()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Master")
Dim n As Long
Dim empname As String
empname = Application.Match(VBA.CStr(Me.Update_record.Value),
sh.Range("C:C"), 0)
sh.Range("A" & empname).Value = Me.First_Name.Value
sh.Range("B" & empname).Value = Me.Last_Name.Value
sh.Range("D" & empname).Value = Me.MainPX.Value
sh.Range("E" & empname).Value = Me.AltPX.Value
sh.Range("F" & empname).Value = Me.Job_Role.Value
sh.Range("G" & empname).Value = Me.WristBand.Value
sh.Range("H" & empname).Value = Me.Team.Value
sh.Range("I" & empname).Value = Me.Unit.Value
Range("A2:J" & n).Sort key1:=Range("A2:A" & n), order1:=xlAscending,
Header:=xlNo
Me.First_Name.Value = ""
Me.Last_Name.Value = ""
Me.MainPX.Value = ""
Me.AltPX.Value = ""
Me.Job_Role.Value = ""
Me.WristBand.Value = ""
Me.Team.Value = ""
Me.Unit.Value = ""
MsgBox "Record has been updated", vbInformation
End Sub
This is where the application is erroring out...It stops here....on this line
empname = Application.Match(VBA.CStr(Me.Update_record.Value),
sh.Range("C:C"), 0)
So the data never gets updated to the row. Below are two screen shots... one of the worksheet and one of the userform.
There are three ways that I can immediatley think to go about it. I haven't tested the first two so let me know if you face any problem.
WAY ONE
Dim fName As String
Dim lName As String
Dim NameToSearch As String
Dim RecRow As Long
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Master")
fName = FirstNameTextbox.Value '<~~ First Name textBox
lName = LastNameTextbox.Value '<~~ Last Name textBox
NameToSearch = fName & ", " & lName
empname = Application.WorksheetFunction.Match(NameToSearch, sh.Range("C:C"), 0)
WAY TWO
This method uses .Find.
Dim fName As String
Dim lName As String
Dim NameToSearch As String
Dim aCell As Range
Dim ws As Worksheet
Dim RecRow As Long
fName = FirstNameTextbox.Value
lName = LastNameTextbox.Value
NameToSearch = fName & ", " & lName
Set ws = ThisWorkbook.Sheets("Master")
With ws
Set aCell = .Columns(3).Find(What:=NameToSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
RecRow = aCell.Row '<~~ This is the row where the data is
Else
MsgBox SearchString & " not Found"
End If
End With
WAY THREE (I prefer This)
Insert a column in the worksheet in Col A and call it ID. This will have unique serial numbers(row numbers?). When reading the item, read that as well and when writing it back to the cells, use that ID to write back. No need to search for the record using Match or .Find
In this case you will always update the row (ID + 1) assuming, the serial number starts at 1 from row 2.
my actual code is :
Option Explicit
Sub SaveMailActiveSheetAsPDFIn2016()
'Ron de Bruin : 1-May-2016
'Test macro to save/mail the Activesheet as pdf with ExportAsFixedFormat with Mail
Dim FileName As String
Dim FolderName As String
Dim Folderstring As String
Dim FilePathName As String
Dim strbody As String
'Check for AppleScriptTask script file that we must use to create the mail
If CheckAppleScriptTaskExcelScriptFile(ScriptFileName:="RDBMacMail.scpt") = False Then
MsgBox "Sorry the RDBMacMail.scpt is not in the correct location"
Exit Sub
End If
'My example sheet is landscape, I must attach this line
'for making the PDF also landscape, seems to default to
'xlPortait the first time you run the code
ActiveSheet.PageSetup.Orientation = xlLandscape
'Name of the folder in the Office folder
FolderName = "TempPDFFolder"
'Name of the pdf file
FileName = "Order " & [C1] & " " & Format(Date, "dd-mm-yyyy") & ".pdf"
Folderstring = CreateFolderinMacOffice2016(NameFolder:=FolderName)
FilePathName = Folderstring & Application.PathSeparator & FileName
'Create the body text in the strbody string
strbody = "Hi " & [C2] & "," & vbNewLine & vbNewLine & _
"Please find attached our new order" & vbNewLine & _
vbNewLine & _
"Thanks"
'expression A variable that represents a Workbook, Sheet, Chart, or Range object.
'Not working if you change activeworkbook, always save the activesheet
'Also the parameters are not working like in Windows
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
FilePathName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False
'Call the MacExcel2016WithMacMailPDF function to save the new pdf and create the mail
'When you use more mail addresses separate them with a ,
'Look in Mail>Preferences for the name of the mail account or signature
'Account name looks like this : "Your Name <your#mailaddress.com>"
MacExcel2016WithMacMailPDF subject:=[C6] & Format(Date, "dd/mm/yy"), _
mailbody:=strbody, _
toaddress:=[C3], _
ccaddress:=[C4], _
bccaddress:=[C5], _
attachment:=FilePathName, _
displaymail:=True, _
thesignature:="", _
thesender:=""
End Sub
I would like that all cells from E column in the print area =0 not to be displayed and that the sheet shrinks itself (like deleting the lines were =0), this before creating the .pdf document and opening mailbox.
I dunno if I'm clear enough sorry
Thank you for your help though
Assuming column E of Sheet1 is the one you want to hide if filled with zeros:
Sub hideZeroFilledColumn()
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("E:E")
rng.EntireColumn.Hidden = (Excel.WorksheetFunction.Count(rng) = _
Excel.WorksheetFunction.CountIf(rng, "0"))
End Sub
Or, if you want to hide just the lines when cell value in column E:E is 0:
Sub hideLineWithZero()
Dim WS As Worksheet
Set WS = ThisWorkbook.Worksheets("Sheet1")
Dim strColumn As String
strColumn = "E" 'If the column you want to check is "E:E"
'Getting first row of printarea and setting "rngPrintStart" to that row in column strColumn
Dim rngPrintStart As Range
'The split is used to separate the start and end of the PrintArea address
'Here we take component "0" of the split, so the start part of the PrintArea
Set rngPrintStart = Range(Split(WS.PageSetup.PrintArea, ":")(0))
Set rngPrintStart = WS.Range(strColumn & rngPrintStart.Row)
'Getting last row of printarea and setting "rngPrintEnd" to that row in column strColumn
Dim rngPrintEnd As Range
'The split is used to seperate the start and end of the PrintArea address
'Here we take component "1" of the split, so the end part of the PrintArea
Set rngPrintEnd = Range(Split(WS.PageSetup.PrintArea, ":")(1))
Set rngPrintEnd = WS.Range(strColumn & rngPrintEnd.Row)
'Merging rngPrintStart and rngPrintEnd ranges from printarea in column strColumn
Dim rngPrintColumnE As Range
Set rngPrintColumnE = WS.Range(rngPrintStart, rngPrintEnd)
Dim rng As Range
Dim rngToHide As Range
'looking in all cells from rngPrintColumnE
For Each rng In rngPrintColumnE
'checking if cell value is equal to 0 and is not empty
If (rng.Value2 = 0) And (rng.Value2 <> "") Then
'Building the range to be hidden
If rngToHide Is Nothing Then 'For the first time when "rngToHide" is not yet set
Set rngToHide = rng
Else
Set rngToHide = Union(rngToHide, rng)
End If
End If
Next rng
'to hide the rows from the previously built range
rngToHide.Rows.EntireRow.Hidden = True
End Sub
I'm assuming you want to hide column E if all the values in it are zero?
Do a sum of the values into another cell (X99 in my example) then use the following code:
With ActiveSheet
If .Range("X99").Value = 0 Then
.Range("e:e").EntireColumn.Hidden = True
Else
.Range("e:e").EntireColumn.Hidden = False
End If
End With
Edit:
You can use Abs(Min(E:E))>0 instead of Sum if you have negative values
For some reason I can't add another answer so here goes with another edit.
To hide rows that have zero in the e column:
Dim i As Integer
Dim pa As Range
Dim ecolnumber As Integer
ecolnumber = 5
Set pa = Range(ActiveSheet.PageSetup.PrintArea)
For i = 0 To pa.Rows.Count
Dim ecell As Range
Set ecell = pa(i, ecolnumber)
ecell.EntireRow.Hidden = ecell.Value = 0
Next
Note the ecolnumber, you may have to change it to reference the correct column.
After you have done all your stuff you can unhide the rows with:
For i = 0 To pa.Rows.Count
Set ecell = pa(i, ecolnumber)
ecell.EntireRow.Hidden = False
Next
The current codes I am working on requires me to rearrange the columns in VBA. It has to arranged according to the header, and the headers are "V-d(1)", "V-g(1)", "I-d(1)", "I-g(1)", and this set repeats for numbers 2, 3, etc etc. (e.g V-d(2), I-g(4)). These data are usually jumbled up and I have to arrange them in ascending numbers.
It does not matter if V-g, V-d, I-d or I-g comes first.
Dim num, numadj As Integer
Dim colu, coladj
Range("A1").Select
Do While Range("A1").Offset(0, i - 1).Value <> ""
colu = ActiveCell.Value
coladj = ActiveCell.Offset(0, 1).Value
num = Left(Right(colu.Text, 2), 1)
numadj = Left(Right(coladj.Text, 2), 1)
If num > numadj Then
colu.EntireColumn.Cut Destination:=Columns("Z:Z")
coladj.EntireColumn.Cut Destination:=colu
Columns("Z:Z").Select.Cut Destination:=coladj
i = i + 1
Else
i = i + 1
End If
Loop
I am very new to VBA so please forgive me for any dumb codes that I have created!!! Thank you in advance everyone!
Consider an SQL and RegEx solution to select columns in a specified arrangement. SQL works in Excel for PC which can access Windows' Jet/ACE SQL Engine to query its own workbook like a database table.
Due to the variable nature of sets ranging 3-10, consider finding the highest number set by extracting the numbers from column headers with RegEx using the defined function, FindHighestNumberSet. Then have RunSQL subroutine call the function to build SQL string dynamically.
Below assumes you have data currently in a tab named DATA with an empty tab named RESULTS which will output query results. Two ADO connection strings are available.
Function (iterating across column headers to extract highest number)
Function FindHighestNumberSet() As Integer
Dim lastcol As Integer, i As Integer
Dim num As Integer: num = 0
Dim regEx As Object
' CONFIGURE REGEX OBJECT
Set regEx = CreateObject("VBScript.RegExp")
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = "[^0-9]"
End With
With Worksheets("DATA")
lastcol = .Cells(7, .Columns.Count).End(xlToLeft).Column
For i = 1 To lastcol
' EXTRACT NUMBERS FROM COLUMN HEADERS
num = Application.WorksheetFunction.Max(num, CInt(regEx.Replace(.Cells(1, i), "")))
Next i
End With
FindHighestNumberSet = num
End Function
Macro (main module looping through result of above function)
Sub RunSQL()
On Error GoTo ErrHandle
Dim conn As Object, rst As Object
Dim strConnection As String, strSQL As String
Dim i As Integer
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' DRIVER AND PROVIDER CONNECTION STRINGS
' strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
' & "DBQ=" & Activeworkbook.FullName & ";"
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='" & ActiveWorkbook.FullName & "';" _
& "Extended Properties=""Excel 8.0;HDR=YES;"";"
' FIRST THREE SETS
strSQL = " SELECT t.[V-d(1)], t.[I-d(1)], t.[I-g(1)]," _
& " t.[V-d(2)], t.[I-d(2)], t.[I-g(2)]," _
& " t.[V-d(3)], t.[I-d(3)], t.[I-g(3)]"
' VARIABLE 4+ SETS
For i = 4 To FindHighestNumberSet
strSQL = strSQL & ", t.[V-d(" & i & ")], t.[I-d(" & i & ")], t.[I-g(" & i & ")]"
Next i
' FROM CLAUSE
strSQL = strSQL & " FROM [DATA$] t"
' OPEN DB CONNECTION
conn.Open strConnection
rst.Open strSQL, conn
' COLUMN HEADERS
For i = 1 To rst.Fields.Count
Worksheets("RESULTS").Cells(1, i) = rst.Fields(i - 1).Name
Next i
' DATA ROWS
Worksheets("RESULTS").Range("A2").CopyFromRecordset rst
rst.Close: conn.Close
Set rst = Nothing: Set conn = Nothing
MsgBox "Successfully ran SQL query!", vbInformation
Exit Sub
ErrHandle:
Set rst = Nothing: Set conn = Nothing
MsgBox Err.Number & " = " & Err.Description, vbCritical
Exit Sub
End Sub
You can sort vertically by a helper row with something like this (tested):
Sub test() ': Cells.Delete: [b2:d8] = Split("V-d(10) V-d(2) V-d(1)") ' used for testing
Dim r As Range: Set r = ThisWorkbook.Worksheets("Sheet1").UsedRange ' specify the range to be sorted here
r.Rows(2).Insert xlShiftDown ' insert helper row to sort by. (used 2nd row instead 1st so that it is auto included in the range)
r.Rows(2).FormulaR1C1 = "=-RIGHT(R[-1]C,LEN(R[-1]C)-3)" ' to get the numbers from the column header cells above, so adjust if needed
r.Sort r.Rows(2) ' sort vertically by the helper row
r.Rows(2).Delete xlShiftUp ' delete the temp row
End Sub
I am trying to build a sub that will enter a formula into a cell, filldown the vlookup formula to lastrow, then copy the formula and pastespecial->values for the entire range. The table I use in vLookup is located in a separate file that is not always stored in the same location. The Table is always formatted the same, but the table size is not always the same.
I have to do this on 4 different worksheets and the column that I have to enter this formula in has a heading of "Order Grade". I use a .Find to return the location of "Order Grade". I then want to enter my Vlookup 1 row below where "Order Grade" is found.
if I enter the formula manually on the worksheet it looks like this:
=VLOOKUP(C2,[newpipe.xlsx]Sheet1!$A$1:$B$376,2,FALSE)
in VBA the formula I want to construct would look something like this:
=vlookup(RC[-1],stringFileName\[newpipe.xlsx]Sheet1!$A$1:LastColumn & LastRow,2,False
With the user choosing the stringFileName using an open file dialog box. LastColumn and LastRow on the chosen sheet should be calculated by the macro.
Here is what I have so far.
Private Function UseFileDialogOpen()
Dim myString As String
' Open the file dialog
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count = 1 Then
myString = .SelectedItems(1)
'MsgBox myString
UseFileDialogOpen = myString
Else
MsgBox ("Failed to properly open file")
myString = "fail"
UseFileDialogOpen = myString
End If
End With
End Function
Sub formatOrderColumn()
Dim strSearch
Dim foundColumn
Dim foundRow
Dim RowBelowSpotFound
Dim fileLocation
strSearch = "Order Grade"
Set aCell = ActiveSheet.Rows(1).Find(what:=strSearch, LookIn:=xlValues, _
Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If Not aCell Is Nothing Then
foundColumn = aCell.Column
foundRow = aCell.Row
spotFound = ColumnLetter(foundColumn) & foundRow + 1
' MsgBox "Value Found in Row " & foundRow & _
" and the Column Number is " & foundColumn
Else
Exit Sub
End If
fileLocation = UseFileDialogOpen()
LastColumn = FindLastColumn(UserSelectedSheet)
LastRow = FindLastRow(UserSelectedSheet)
Range(RowBelowSpotFound).Formula = _
"=vlookup(RC[-1], [" & fileLocation & "]Sheet1!$A$1:" & LastColumn & lastrow & ",2,False"
End Sub
I do not know how to get the lastrow and lastColumn from the user chosen file. I have functions that do that for any Worksheet that is passed to them. I realize I did a pretty poor job explaining my situation and am not at all sure I am going about this the best way. If you have any questions let me know and I'll do my best to clarify. I'll be leaving the office soon so may not be able to reply until the morning.
Here is new formula. I get error on last line when I try to set the offset cell formula to the string value. The string value is correct. I get the same error if I try to set the cell value directly without using the mystring holder to first build the string. "application or object defined error"
Sub vlookupOrderGrade()
Dim strSearch
Dim fileLocation
Dim aCell As Range
Dim aCellString
Dim myString As String
strSearch = "Order Grade"
Set aCell = ActiveSheet.Rows(1).Find(what:=strSearch, LookIn:=xlValues, _
Lookat:=xlWhole, MatchCase:=True)
If Not aCell Is Nothing Then
fileLocation = UseFileDialogOpen()
If fileLocation <> "fail" Then
'replace last "\" with a "["
fileLocation = StrReverse(fileLocation)
fileLocation = Replace(fileLocation, "\", "[", 1, 1)
fileLocation = StrReverse(fileLocation)
'build string
myString = "=vlookup(" & _
ColumnLetter(aCell.Column - 1) & aCell.Row + 1 & _
", '" & fileLocation & "]Sheet1'!$A:$B,2,False"
MsgBox (myString)
'set cell to string
aCell.Offset(1, 0).Formula = myString
End If
Else
Exit Sub
End If
End Sub
Untested:
Sub formatOrderColumn()
Dim strSearch
Dim fileLocation
strSearch = "Order Grade"
Set aCell = ActiveSheet.Rows(1).Find(what:=strSearch, LookIn:=xlValues, _
Lookat:=xlWhole, MatchCase:=True)
If Not aCell Is Nothing Then
fileLocation = UseFileDialogOpen()
If fileLocation <> "fail" Then
aCell.Offset(1, 0).Formula = "=vlookup(" & _
aCell.Offset(1, -1).Address(False, False) & _
", '[" & fileLocation & "]Sheet1'!$A:$B,2,False"
End If
Else
Exit Sub
End If
End Sub