Retrieve Cell Value from another workbook using a reference cell location - excel

So I've done some digging and found the pieces I think are necessary to achieve my goal but I am having trouble putting the pieces together in the correct order. I have achieved referencing a cell value from a different workbook using its file location and copying that value to my active workbook.
My problem comes when I want that file location to come from a reference cell within my active workbook, NOT from a file location embedded in the code itself. The idea is that other users can simply copy their file location to the reference cell and the macro pulls the necessary values from that file.
Here is my code that works using with the location coming from the code itself
Private Sub CommandButton1_Click()
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open("R:\Branches\XXX\XXX\XXX\MASTER LOAN MEMO 8-14.xlsx")
ActiveWorkbook.Sheets("Sheet1").Range("H3") = WBK.Sheets("Master Input").Range("B58").Value
WBK.Close
Set XL = Nothing
End Sub
Here is my modified version to try to accomplish what I explained earlier:
Private Sub CommandButton2_Click()
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Dim Location As String
Location = ActiveWorkbook.Sheets("Sheet2").Range("B2").Value
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(Location)
ActiveWorkbook.Sheets("Sheet1").Range("H3") = WBK.Sheets("Master Input").Range("B58").Value
WBK.Close
Set XL = Nothing
End Sub
I'm getting a Runtime Error 1004 stating the file location cannot be found. Any help would be much appreciated.

I can't replicate the problem EXCEPT when I use a deliberately bad file location (i.e., a location that doesn't exist in my environment). Since it looks like your directory structure can be many levels deep, and since you're referencing a drive letter instead of a server name, perhaps the location is mis-spelled? Try moving the file you're looking for to your C drive, change the value in Sheet2.B2 accordingly and test that.
BTW, I'm not having problems copying values that have use various functions, ampersands and concatenations.

Related

Using VBScript to Change Excel View to Page Layout

I need to use VBScript to change all of the sheets in an excel workbook to Page Layout View instead of the default view. However, I cannot figure out how to do that in VBS. With VBA, the code I've been using (with a while loop to go over each sheet) is
With ActiveWindow
.View = xlPageLayoutView
End With
which serves my purposes fine. But I need to do this in VBS. I think it has something to do with the Application object, though I'm not sure. Any help would be appreciated.
Edit: here's a sample of the code I've written with declarations and things. It's basically iterating over a number of sheets in a workbook and setting them all (or trying to) to Page Layout view. Missing from this segment is the sub where I populate the workbook with new sheets matching the entries from Names().
Dim destFile, objWorkbook
Set destFile = CreateObject("Excel.Application")
Set objWorkbook = destFile.Workbooks.Add()
objWorkBook.SaveAs(strPath)
Sub OverNames()
For i = 1 to 9
SetPagelayout(i)
Next
End Sub
Sub SetPageLayout(hNum)
Dim houseSheet, sheetName
'retrieves sheet name from array Names()
sheetName = Names(hNum, 0)
Set houseSheet = destFile.Worksheets(sheetName)
houseSheet.Window.View = xlPageLayoutView
End Sub
VBA already has excel and the workbook loaded. With VBS, you need to create an excel object and open your workbook with it. Also, VBA has static variables defined for excel settings, which you will have to define yourself in VBS.
Dim objExcel
Dim excelPath
Dim xlPageLayoutView=3 ' https://msdn.microsoft.com/en-us/library/office/ff838200.aspx
excelPath = "C:\scripts\servers.xlsx"
objExcel.DisplayAlerts = 0
Set objExcel = CreateObject("Excel.Application")
In order to change the state of a window, you have to access the window object. In excel there are Workbooks, which contain collections of Worksheets and Windows. The application also contains a collection of all windows in all worksheets. In the workbook window collection, the active window is always accessed through index 1.
Set currentWorkBook = objExcel.ActiveWorkbook
Set currentWorkSheet = currentWorkBook.Worksheets("Sheet Name Here")
currentWorkSheet.Activate
Set currentWindow = currentWorkBook.Windows(1)
currentWindow.View = xlPageLayoutView

SSIS Script Task Delete Row from excel Sheet

I have an SSIS package that creates and populates an excel sheet, it creates the sheet from a template file.
One of the issue's I had was that excel would change the format of the rows. I did a work around of inserting a header row and hiding it.
However I now need to script a VB task in SSIS that opens the excel sheet and deletes that specific row.
I've seen some articles online however have not been able to find any code I can try and replicate and my VB knowledge is very limited and I am really struggling.
SO far i've figured out how to delete the row.
Sub DeleteRow1()
Rows(4).Delete
End Sub
However i need to assign file strings and get the file to open and close as well...
after some discussions with a programmer here i managed to get some script to do exactly what I needed. Posting as an answer for anyone else out there who ever needs to do this in SSIS.
Dim xlApp As Excel.Application
Dim xlSheet As Excel.Worksheet
xlApp = New Excel.Application
xlApp.Workbooks.Open(Dts.Variables("NewFileName").Value.ToString)
xlSheet = xlApp.Workbooks(1).ActiveSheet
xlSheet.Rows(4).Delete()
xlApp.Workbooks(1).Save()
xlApp.Workbooks(1).Close()
xlSheet = Nothing
'
Dts.TaskResult = ScriptResults.Success
Uses a variable in SSIS to get the file name. This works perfectly although you do need to add Microsoft.Office.Interop.Excel Reference.
Sub deleteRow1()
Dim wkbk As Workbook
'You can also use an input box like this
' Dim wkbkname As Variant
' wkbkname = InputBox("Enter Workbook Name here.")
' Use wkbkname instead of wkbk then
Set wkbk = "Filename"
wkbk.Sheets(1).Rows(4).delete
End Sub
I hope that's what you were looking for.

open specific worksheets in excel through VB

I have the the following code which creates a csv file for an excel file .It is working fine if i specify the worksheet number (like 1,2 etc) but i want to specify the sheet name.The sheet name may contain some space before or after the name.And this is the problem.I think i should use regular expression but i am not able to figure out how.If the file does contain extra space and if i do not handle it i get a subscript out of range error .
src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dim mine(1)
mine(0)="
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)
oBook.Worksheets("Failure Report").Activate
oBook.SaveAs mine(0), csv_format
oExcel.Quit
If the worksheet name can only be approximated when you try to reference it, then you don't have a lot of choice but to loop over the target workbook's worksheets to find a match. Perhaps something like this (I'm assuming you can adapt this to suit your specific requirements):
Sub test()
Dim ws As Worksheet
Dim aWsName As String
aWsName = "Failure Report"
For Each ws In ActiveWorkbook.Worksheets
If InStr(1, ws.Name, aWsName) > 0 Then
ws.Activate
ActiveSheet.[A1] = "Matched!"
End If
Next
End Sub
Although not perfect for all situations, the code is trying to find the worksheet name aWsName in the name of one of the active workbook's worksheets. The reason it's not perfect is because it doesn't care what characters come before or after the string aWsName that you're looking for. If the names are sufficiently different, then this shouldn't be a problem. You can at least give it a go and see how it works for you.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

I'm attempting to copy the contents of a text box from one workbook to another. I have no problem copying cell values from the first workbook to the 2nd, but I get an object required error when I attempt to copy the text box. This macro is being run from the workbook containing the data I want copied. Using Excel 2007 Code:
Sub UploadData()
Dim xlo As New Excel.Application
Dim xlw As New Excel.Workbook
Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
xlo.Worksheets(1).Cells(2, 1) = Range("d4").Value 'Copy cell content (this works fine)
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text 'This gives me the object required error
xlw.Save
xlw.Close
Set xlo = Nothing
Set xlw = Nothing
End Sub
Thanks for any help.
The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.
Sub UploadData()
Dim xlo As New Excel.Application
Dim xlw As New Excel.Workbook
Dim myWb as Excel.Workbook
Set myWb = ActiveWorkbook
Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text
xlw.Save
xlw.Close
Set xlo = Nothing
Set xlw = Nothing
End Sub
If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).
I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".
EDIT
It looks like you may be able to use the GetObject function to pull the textbox from the workbook.
The issue is with this line
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.
Hence replace this with
xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text

How to get reference to an open Excel spreadsheet from Word?

I have some VBA code that copies stuff from Excel and pastes it into Word. The problem I'm having is how to open the spreadsheet. I can open it using an absolute path reference by
Workbooks.Open "C:\path\filename.xls"
I would prefer to reference the spreadsheet using a relative path reference. I was able to find code for relative path references from an Excel workbook to another one but it doesn't seem to work if you're doing it from Word.
Add a reference to Excel object library, then create an object in code and use that object to control an instance of Excel. Just make sure to avoid things like ActiveWorkbook, just in case.
After adding the reference:
Sub DoStuffWithExcelInWord()
Dim xl As Excel.Application
Dim wkbk As Excel.Workbook
Dim wk As Excel.Worksheet
Set xl = CreateObject("Excel.Application")
Set wkbk = xl.Workbooks.Open("C:\test.csv")
Set wk = wkbk.Sheets(1)
Debug.Print wk.Cells(1, 1).Value
xl.Quit
Set wk = Nothing
Set wkbk = Nothing
Set xl = Nothing
End Sub
You can create something very similar using Excel to automate Word too, if that's more of what you're looking for.

Resources