I'm writing a script that requires opening a second workbook and running a VLOOKUP in the second workbook. It works perfectly when the filename of the second workbook is "testlookup.xlsx" but when I changed the filename to "hippity hop 1251225253.xlsx", it opens a window that says "Update Values: 1251225253" and then the VLOOKUP fails. How can I get the code to work regardless of the filename?
fpath = Application.GetOpenFilename(, , "Select the CMS All Assets exported CSV")
fname = Dir(fpath)
Workbooks.Open (fpath)
Set openedBook = Application.ActiveWorkbook
Set assetBook = openedBook.Worksheets(1)
ActiveWindow.WindowState = xlMinimized
checkWkbk.Activate
With dupeSheet
'determine last row
lr = .Cells(Rows.count, 1).End(xlUp).Row
'vlookup from C2:CEnd
.Range(.Cells(2, 3), .Cells(lr, 3)).FormulaR1C1 = _
"=VLOOKUP(RC[-2], " & CStr(fname) & "!C1:C2, 2, FALSE)"
End With
If your description of the filenames is correct, the problem is that you're using a file name with space characters in it, which is throwing the VLookup off. You need to put single-quote characters around the file name in the formula, thus:
"=VLOOKUP(RC[-2], '" & CStr(fname) & "'!C1:C2, 2, FALSE)"
I may be off base with this bit, since you said it works when you don't have spaces in the file names, but you should also include the worksheet name in the formula string, so your formula would look more like this:
"=VLOOKUP(RC[-2], '[" & CStr(fname) & "]" & assetBook.name & "'!C1:C2, 2, FALSE)"
Part of what may be happening is you use the ActiveWorkbook to find the workbook you need versus finding the workbook by the correct name. I use the below subroutine for this purpose:
Sub Get_Workbook_Object(sPath As String, wbHolder As Workbook)
Dim wb As Workbook
If Len(sPath) > 0 Then
ThisWorkbook.FollowHyperlink (sPath)
Else
Exit Sub
End If
For Each wb In Workbooks
If wb.FullName = sPath Then
Set wbHolder = wb
Exit Sub
End If
Next
End Sub
To use this code you could add the subroutine to your module and then call it with something like:
Get_Workbook_Object fPath, openedBook
Also Dir() isn't going to return a fullpath, it is only going to return the appropriate filename. For example, it may return "Hippity Hop.xlsx" instead of "C:Users\Hippity Hop.xlsx" where the first part is the actual filepath. You may want to use something like this instead:
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Please select the CMS All Assets exported CSV"
.Show
If .SelectedItems.Count = 1 Then
fpath = .SelectedItems(1)
Else
MsgBox "Please choose at least one file"
Exit Sub
End If
End With
This will return the full path of the file.
Related
I have a workbook (let's call it "GENERAL") which activates via macro a lot of other workbooks in a specific folder and pulls specific data over to GENERAL in order to build a total sum. I would like to automatically create a hyperlink on one of the copied values leading back to the specific workbook in order to be able to trace errors quickly. My code is the following:
MyPath = "Y:\test_workbook"
MyFile = Dir(MyPath)
Do While MyFile <> ""
If MyFile Like "*.xls" Or MyFile Like "*.xlsx" Then
Workbooks.Open MyPath & MyFile
Sheets(1).Select
Range("A1") = myValue
Range("A1") = CDate(myValue)
a = Range("A2").Value ' here file-title
b = Range("A3").Value
c = Range("A4").Value
f = Range("B1").Value
ActiveWorkbook.Close SaveChanges:=True
End If
Workbooks("GENERAL.xlsm").Activate
Sheets("total").Cells(i, j) = a
Sheets("total").Cells(i, j + b) = c
i = i + 1
MyFile = Dir
Loop
So: I want to create a Hyperlink in the workbook GENERAL which is mapped on the cell containing the A2-cell-information of the correlated workbook which provides the information and leads back to it.
Does anybody have a clue how this is done ?
I'm afraid I don't understand your context, but here's how you create hyperlink in Excel VBA:
With worksheet
.Hyperlinks.Add Anchor:=.Range("A2"), _
Address:="http://www.stackoverflow.com", _
ScreenTip:="Stack Overflow", _
TextToDisplay:="StackOverflow"
End With
So I am trying to create a workbook that uses multiple references from a worksheet of the initial data to auto fill cells in different worksheets to produce Forms (pre-formated worksheets). For one of the worksheets, I need to save it on a separate network drive as its own .xlsx workbook. So far, the code I have developed creates the new workbook, but the cells all still contain the original formulas that reference the original workbook. Is there a way, when saving into the new workbook, to convert the cells to values? Here is the sub I have in place. TIA
Private Sub SaveBidTab1_Click()
' Saves the BidTab in the Current Year's Bid Tabs Folder in
' Dave's Snapserver Construction Files
Dim BTFName As String 'this will be the name of the new file name saved in the Bid Tabs Folder
Dim BTFfolder As String 'This is the folder to save the form into
Dim BTFDate As String 'This is the date to choose which year's folder to use
Dim ProjectShortName As String 'This is the short name for the project for the file name
Dim NewBook As Workbook ' This is temp workbook that the new bid tab sheet will be saved as
If Worksheets("BidTab").Range("G12") = "" Then
ans = MsgBox("This form is not ready to be saved", vbOKOnly, "Bid Tabs")
Select Case ans
Case vbOK
Exit Sub
End Select
End If
'Requests user to enter in short name for project
Msg = "Enter Project Short Name"
ProjectShortName = InputBox(Msg, "Save As")
' TRIAL is added here until project is compelted.
BTFName = "TRIAL " & Worksheets("Initial Entry").Range("B5") & " " & ProjectShortName & _
" " & "Bid Tab Results" & " " & Worksheets("BidTab").Range("L5")
' Add in a cancle option to this msgbox
MsgBox BTFName
BTFDate = Year(Now())
BTFfolder = "M:\DotserverD\Daves Snapserver Files Construction Files\Bid Tabs\" & BTFDate _
& "\County"
Debug.Print BTFfolder
Set NewBook = Workbooks.Add
ThisWorkbook.Worksheets("BidTab").Copy Before:=NewBook.Sheets(1)
NewBook.SaveAs Filename:=BTFfolder & "\" & BTFName & ".xlsx", FileFormat:=xlOpenXMLWorkbook
End Sub
ThisWorkbook.Worksheets("BidTab").Copy Before:=NewBook.Sheets(1)
Put this after the above statement:
With NewBook.Sheets(1).UsedRange
.Value = .Value
End With
This will remove the links and keep only the values in the new worksheet.
I have this in a similar book. You can probably simplify it.
Dim shShape As Shape
For i = 1 To UBound(sheetNames)
mSaveWorkbook.Sheets(i).Name = sheetNames(i)
If mSaveWorkbook.Sheets(i).Shapes.Count > 0 Then
For Each shShape In mSaveWorkbook.Sheets(i).Shapes
If shShape.Type = msoFormControl Then
shShape.Delete
End If
Next shShape
End If
Next i
End If
I'm trying to finish a script that will allow a user to select another excel file when a cell is double clicked, then that excel file is used to drop in a formula into the main excel file.
I cannot use the cell values alone because being able to see the file path in the formula bar when the script is complete is required. So the issue is that the formula being entered does not match the string text that it should be pulling from.
For clarification, the string I use called FormulaPath ends up being a formula ending "...\00975-006-00[00975-006-00.xls]QuoteDetails'!" and this would be the correct formula.
But when I use this to enter the formula into a range:
Range("A1").Formula = "=" & FormulaPath & "$C$100"
The actual formula ends up being entered as "...[00975-006-00[00975-006-00.xls]Quote Details]00975-006-00[00975-006-00.xls]Q'!$C$100
Notice the repetition?
I'm on mobile right now, so forgive me if the formatting is wacky. Full script below. Thanks!
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim ImportWB, QuoteWB As Workbook
Dim AdInsWS, AdInsCostWS As Worksheet
Dim ImportPathName As Variant
Dim FormulaPath As String
Set QuoteWB = ThisWorkbook
Set AdInsWS = QuoteWB.Sheets("Ad-Ins")
Set AdInsCostWS = QuoteWB.Sheets("Ad-ins cost")
If Not Intersect(Target, Range("B:B")) Is Nothing Then
'set default directory
ChDrive "Y:"
ChDir "Y:\Engineering Management\Manufacturing Sheet Metal\Quotes"
'open workbook selection
ImportPathName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Please select a file")
If ImportPathName = False Then 'if no workbook selected
MsgBox "No file selected."
ElseIf ImportPathName = ThisWorkbook.Path & "\" & ThisWorkbook.Name Then 'if quote builder workbook selected
MsgBox "Current quote workbook selected, cannot open."
Else
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Workbooks.Open Filename:=ImportPathName, UpdateLinks:=False
Set ImportWB = ActiveWorkbook
FormulaPath = "'" & ImportWB.Path & "[" & ImportWB.Name & "]Quote Details'!"
AdInsCostWS.Range("B3").Formula = "=" & FormulaPath & "$C$100"
ImportWB.Close
End If
Cancel = True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
End Sub
I got your script to work by simply adding a backslash to the FormulaPath string:
FormulaPath = "'" & ImportWB.Path & "\[" & ImportWB.Name & "]Quote Details'!"
ImportWB.Path is importing the Path with the excel name, split the path string
I am trying to save a copy of a worksheet to a specific folder based on cell B8 and name the .xlsx file based on the cell range B8 too.
For example, a user first creates a new folder named "test1", & then enters this folder name/text into cell "B8". He/she will activate the macro after completing their work on the worksheet, & it will save a copy to the folder named "test1" and name the .xlsx file as "test1". (So the .xlsx file will be named as "testfolder1" and the folder where it is stored is also called "test1")
I am using the following code to save a copy of the worksheet to a folder. Just can't figure out how to include the cell B8 into the SaveAs line. Too new with VB to figure it out.
Sub SaveForm()
exampleForm = Range("B8").Value
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveSheet.Copy
With ActiveWorkbook.ActiveSheet
.Range("42:" & Rows.Count).EntireRow.Delete xlShiftDown
.Range(.Cells(1, "J"), .Cells(1, Columns.Count)).EntireColumn.Delete xlToRight
.Parent.SaveAs "C:\Users\JohnSmith\Desktop\ExtractedWorksheet\" & exampleForm & ".xlsx"
.Parent.Close False
End With
End Sub
Appreciate any input and hopefully my ending goal is understandable.
-Thanks!
I think this is what you're after, give it a try:
Sub SaveForm()
Static Path as string
Static FileName as string
if len(Path) = 0 then
Path = Range("B8")
if right(Path,1) <> "\" then
'make sure the path is "\" terminated
Path = Path & "\"
End if
else
FileName = Range("B8")
'Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveSheet.Copy 'not sure why you're doing this, but do so if it makes sense elsewhere in your code
With ActiveWorkbook.ActiveSheet
.Range("42:" & Rows.Count).EntireRow.Delete xlShiftDown
.Range(.Cells(1, "J"), .Cells(1, Columns.Count)).EntireColumn.Delete xlToRight
.Parent.SaveAs "C:\Users\JohnSmith\Desktop\ExtractedWorksheet\" & Path & _
FileName & ".xlsx"
.Parent.Close False
End With
Path = ""
FileName = ""
End if
End Sub
If you call this code from your worksheet_OnChange event, then when cell B8 is updated, it will:
check to see if you have a Path stored. If not, assume this is the Path
If you have a Path already, assume this is the FileName and save it.
Leave the 'Application.ScreenUpdating` commented out until everything is working OK, then put it back in. Makes figuring out what's going on much easier.
UPDATE based on your latest comment on OP:
Sub SaveForm()
'Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveSheet.Copy 'not sure why you're doing this, but do so if it makes sense elsewhere in your code
With ActiveWorkbook.ActiveSheet
.Range("42:" & Rows.Count).EntireRow.Delete xlShiftDown
.Range(.Cells(1, "J"), .Cells(1, Columns.Count)).EntireColumn.Delete xlToRight
.Parent.SaveAs "C:\Users\JohnSmith\Desktop\ExtractedWorksheet\" & _
Range("B8") & "\" & FileName & ".xlsx"
.Parent.Close False
End With
Path = ""
FileName = ""
End Sub
Here is one that I have created for a project that I worked on.
I first named a cell (through Excel user interface-formula-name
manager-define name) and called it prform_prnumber.
I passed the value in that to a variant variable in vba and called it prnumber.
I then used that variable as name in the exporttopdf method.
I kept the path as that of the workbook.
This code will run (once the button is clicked) in the active worksheet:
Sub exporttopdf()
Dim prnumber As Variant
Set prnumber = ActiveWorkbook.Names("prform_prnumber").RefersToRange
ActiveSheet.ExportAsFixedFormat xlTypePDF, ActiveWorkbook.Path & "/" & filesavename & ".pdf", , , False
End Sub
I am a total dummy as for vb and excel, have tried to combine 2 macros that I have found around here, into 1, but obviously did something terribly wrong and now i'm stuck.. First I just used this macro (saved it in as personal.xlsb so as to be able to use it in any workbook)
Sub CSVFile()
Dim SrcRg As Range
Dim CurrRow As Range
Dim CurrCell As Range
Dim CurrTextStr As String
Dim ListSep As String
Dim FName As Variant
FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
ListSep = ";"
If Selection.Cells.Count > 1 Then
Set SrcRg = Selection
Else
Set SrcRg = ActiveSheet.UsedRange
End If
Open FName For Output As #1
For Each CurrRow In SrcRg.Rows
CurrTextStr = ìî
For Each CurrCell In CurrRow.Cells
CurrTextStr = CurrTextStr & """" & GetUTF8String(CurrCell.Value) & """" & ListSep
Next
While Right(CurrTextStr, 1) = ListSep
CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
Wend
Print #1, CurrTextStr
Next
Close #1
End Sub
That plus the GetUTF8String function code. Now that was working fine. Then I have thought well why not just experiment with my limited (that is a serious understatement) vb understanding, added the following code and changed the CSVFile sub into a function, which I then called from the sub below, with the output file name as a parameter (to be used instead FName = Application.GetSaveAsFilename). I thought yeah, this code saves all sheets automatically, now let's just make sure that the encoding and delimiter/enclosure setting function runs before each sheet is saved. It doesn't seem right but I thought hey why not try..
Public Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven
' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
' Save the file in current director
OutputPath = ThisWorkbook.Path
If OutputPath <> "" Then
Application.Calculation = xlCalculationManual
' save for each sheet
For Each Sheet In Sheets
OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv"
' make a copy to create a new book with this sheet
' otherwise you will always only get the first sheet
Sheet.Copy
' this copy will now become active
CSVFile(OutputFile)
ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Next
Application.Calculation = xlCalculationAutomatic
End If
Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Exit Sub
Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
"Source: " & Err.Source & " " & vbCrLf & _
"Number: " & Err.Number & " " & vbCrLf & _
"Description: " & Err.Description & " " & vbCrLf
GoTo Finally
End Sub
Saved that and with that I have managed to achieve something very different. On opening any workbooks, that macro runs and opens up my sheets from that particular workbook as csv files (without saving them). Now I am like Alice in Wonderland. How come it is running on file open? That is not desirable, so I went back to the macro code and changed it back to just the csvfile sub. Well that didn't help, no idea what I did there, was definitely editing the same macro... So I deleted the macro, the modul, I cannot imagine where the thing now is but it's still running + I get this warning that macros were deactivated. Can't get rid of it! Now lads, I'm sorry for the total lack of professionality from my side, this was just supposed to be a small favor for a client, without wasting loads of time learning vb, coz my boss doesn't like that... I am of course interested in how to achieve the goal of saving the sheets automatically after setting the deimiter and enclosure in them. And at this moment I am very interested in how to get rid of that macro and where it is hiding.. What have I done?! Thank you for your patience!
I think the problem lies with the line
OutputPath = ThisWorkbook.Path
Because you are running this from your personal.xlsb which is stored in your XLSTART folder it has created the CSV files in the same location. When Excel starts it will try and load any files that it finds in that location.
Just locate your XLSTART folder and delete any CSV files you find there.
Try using
OutputPath = ActiveWorkbook.Path
XLSTART folder location, dependent on your system, is probably something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\Excel\XLSTART