VBA opening two worksheets importing different data in each - vba

Hi im new to VBA excel and i want to import data this part i can do fine but in the same sub i want to open a new worksheet in the same workbook and in that worksheet i want to keep the file names of the data i imported from.
Sub GetData()
Dim path As Variant
Dim excelfile As Variant
Dim data_file(1 To 100) As String
path = "C:\dummmy\"`
main_file = ActiveWorkbook.Name
excelfile = Dir(path & "*.xls")
Do While excelfile <> ""
data_file(k + 1) = excelfile
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Test"
ActiveSheet.Paste = datafile(k+1)
End With'
rest of the code the problem i have having is just putting the address of the file in a different worksheet

If I understand your question correctly, you want to know how to work with different worksheets within the same Sub?
That's rather straight forward. Instead of using "ActiveSheet" or anything of the sort, just use their qualified equivalents.
Example:
ThisWorkbook.Worksheets("Data").[...]
ThisWorkbook.Worksheets("Filenames").[...]
This syntax will enable you to operate on specific worksheets. You can either use their name (in my example "Data" and "Filenames") or their position (0, 1, 2 , 3, ...) with 0 being the leftmost worksheet.
When using this syntax it won't matter which worksheet is active, you can do operations on all available worksheets.

Related

Excel VBA: Getting cell value from unopened .xlsx file

So basically I want to write Macros that automatically (in other document) counts range value based on other cell value and then exports it to the template excel file.
I have this code that gets the path to the file from which the data should be extracted:
Sub GetFilePath()
Dim objFSO As New FileSystemObject
Dim BBuy, SSell As String
Set myFile = Application.FileDialog(msoFileDialogOpen)
With myFile
.Title = "Choose File"
.AllowMultiSelect = False
If .Show <> -1 Then
Exit Sub
End If
Fileselected = .SelectedItems(1)
End With
Then value of Fileselected = "C:\Users\ABC\Desktop\report sample.xlsx"
How can I then reference this Excel file in an =SUMIF formula?
I tried something like as below but didn't really work, and also Google did not really help:
BBuy = "Buy"
Fileselected.Formula = "=sumif(A2:A2500, BBuy, N2:N2500)"
Any suggestions would be much appreciated!
To make the formula easier to read, I declared the SumIf criteria's and a variable X which is where the output of SumIf will be stored.
Dim MyRange1 as Range
MyRange1 = myFile.Sheets("Your Sheet Name Here").Range("A2:A2500")
Dim MyRange2 as Range
MyRange2 = myFile.Sheets("Your Sheet Name Here").Range("N2:N2500")
Dim BBuy as String
BBuy = "Buy"
Dim X as Variant
X = Application.WorksheetFunction.SumIf((MyRange1, BBuy, MyRange2)
You dont have to declare these as variables as you can just reference them in the formula and reduce the above code down to one line (2 lines including "Dim X as Variant"). For instance, to replace your ranges and criteria in the formula:
X = Application.WorksheetFunction.SumIf(myFile.sheets("Your Sheet Name Here").Range("A2:A2500), "Buy", myFile.Sheets("Your Sheet Name Here").Range("N2:N2500))
Now you have the answer you want stored in the variable "X". You can just set a range on your current workbook to equal X if you just want to value pasted somewhere.
Heyho,
if you want to refer on a range or cell of another sheet you have to try it like the following:
'path[filename.xls]Sheetname'!$A$2:$A$2500
Did you try to use that already?

How to pass a number as string argument in workbook object (excel)

I am using a for loop to process data of 300 SKUs with some of them having SKU code as purely numeral. The raw data for each SKU is in separate file with both the workbook and worksheet name same as the SKU code.
Error I am facing is index out of range as in:
Workbooks(wbnamex).Sheets(wbnamex).Cells(k, 2)
wbnamex contains SKU code and the ones as numerals are resulting in error. The object workbook is taking it as serial number rather than name.
How to go pass the purely numeral SKU code as String?
This is something that will do the job:
Option Explicit
Public Sub TestMe()
Dim strName As String
Dim wb As Workbook
Dim wsAny As Worksheet
Dim ws As Worksheet
strName = "Text"
Set wb = Workbooks.Open(ThisWorkbook.Path & "\" & strName & ".xlsm")
For Each wsAny In wb.Worksheets
If wsAny.Name = strName Then
Set ws = wsAny
End If
Next wsAny
Debug.Print ws.Cells(1, 1)
End Sub
You need an excel file named Text.xlsm with a Worksheet named Text as well. Then it will show you the Value of the A1 cell of this worksheet of this workbook.
There are other ways to do it, but this one works. The Text file should be in the same folder as the file, in which this code is present. The Excel file Text should be closed as well.
You can edit the code further, to make it work for other folders and with a file, that is already opened.

Excel VBA writes data to second workbook, but starts opening read-only versions because " _ is already open

I have some VBA script in one Excel Workbook that has three subs that each either read from a second Workbook. Each of the subs uses the following algorithm (simplified to distill the interaction with the second book):
Public Sub EditRemote()
Dim remoteDataSheet As Worksheet
Dim source As String 'Source worksheet name
Dim target As String 'Target worksheet name
Dim path As String
Dim wkbName As String
source = "CountData"
path = ThisWorkbook.Worksheets("Parameters").Range("B2").Value
wkbName = ThisWorkbook.Worksheets("Parameters").Range("A2").Value
target = "CountData"
Application.EnableCancelKey = xlDisabled
Set localDataSheet = ThisWorkbook.Sheets(source)
If Not WorkbookIsOpen(wkbName) Then
Workbooks.Open (path)
End If
Set remoteDataSheet = Workbooks(wkbName).Sheets(source)
remoteDataSheet.Cells(1,1) = localDataSheet.Cells(1,1)
remoteDataSheet.Cells(1,2) = localDataSheet.Cells(1,2)
Workbooks(wkbName).Close SaveChanges:=True
End Sub
Function WorkbookIsOpen(targetWorkbook As String) As Boolean
Dim testBook As Workbook
On Error Resume Next
Set testBook = Workbooks(targetWorkbook)
If Err.Number = 0 Then
WorkbookIsOpen = True
Else:
WorkbookIsOpen = False
End If
End Function
There is also a pivot table in this Workbook that draws its data from the second file though an external data connection as well. The issue that is plaguing me is that it seems that not initially but after a few operations, these subs stop making the edits properly and instead it opens a read only copy of the second Workbook. When I try to open the second workbook manually I get a message saying that the file is already open and is locked for editing. Right now both files are local to my computer and couldn't be opened by anyone else. What am I missing to be sure that I can make the code work as intended?
I made some modification to your code, ran it a few times, and didn't get your "Read-only" message.
In your code the line of declaring localDataSheet is missing, added Dim localDataSheet As Worksheet , also added Dim remoteWb As Workbook for the remote workbook.
(didn't modify your Funtion WorkbookIsOpen code).
Sub EditRemote Code
Option Explicit
Public Sub EditRemote()
Dim remoteDataSheet As Worksheet
Dim localDataSheet As Worksheet
Dim source As String 'Source worksheet name
Dim target As String 'Target worksheet name
Dim path As String
Dim wkbName As String
Dim remoteWb As Workbook
source = "CountData"
path = ThisWorkbook.Worksheets("Parameters").Range("B2").Value
wkbName = ThisWorkbook.Worksheets("Parameters").Range("A2").Value
target = "CountData"
Application.EnableCancelKey = xlDisabled
Set localDataSheet = ThisWorkbook.Sheets(source)
' check if workbbok already open
If Not WorkbookIsOpen(wkbName) Then
Set remoteWb = Workbooks.Open(path)
Else
Set remoteWb = Workbooks(wkbName) ' workbook is open >> set remoteWb accordingly
End If
Set remoteDataSheet = remoteWb.Sheets(source)
remoteDataSheet.Cells(1, 1) = localDataSheet.Cells(1, 1)
remoteDataSheet.Cells(1, 2) = localDataSheet.Cells(1, 2)
Workbooks(wkbName).Close SaveChanges:=True
End Sub
Just to verify the data in your Excel "Parameters" sheet, the screen-shot below shows the data I used for my testing.
Cell A2 contains the "Clean" workbook name.
Cell B2 contains workbbok "full" name - path + "clean" workbook name.
After some further testing to diagnose the issue, I found that there was nothing wrong with the VBA code, but rather the external data connection to the remote Workbook was locking that Workbook every time I refreshed the data in the pivot table that used the external data connection as its source. It isn't unlocking the file when it is done refreshing, and that leaves the file locked until I close the Workbook with the pivot table. Now I just need to solve that problem.

Paste Values into new worksheet for all Open Worksheets including pictures

I am trying to create a renamed copy of all active workbooks (even non macro-enabled ones) without formulas, possibly by pasting values but without modifying images. I am working with Excel 2007.
My process would ideally be to:
1) Create a do while there are xls files loop that converts all xls files to xlsm. One possible addition would be an array to store A)the worksheet name(s) B)Its tabs name and their status
2) Run a for each or for loop that automatically pastes values for all active worksheets include those with graphs or other images into a new document that has the same name with all small addition at the end.
3) Convert my newly-named files containing values only into xls.
One issue I am running into when I try to do this has to do with links. The initial worksheets have formulas with links that do not automatically update. When I do this, the formulas in the original worksheet with link references tend to get corrupted.
Here is a general macro I found for pasting values:
Sub test()
Dim MyNames As Range, MyNewSheet As Range
Set MyNames = Range("R5").CurrentRegion ' load contigeous range into variable
For Each MyNewSheet In MyNames.Cells ' loop through cell children of range variable
Sheets.Add.Name = MyNewSheet.Value
Next MyNewSheet
MyNames.Worksheet.Select ' move selection to original sheet
End Sub
I think this is what you're asking for:
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim counter As Integer
Dim filePath As String
Set wb = ActiveWorkbook
countet = 1
filePath = "c:/" 'Enter your destination folder here
For Each ws In wb.Sheets
Sheets("Sheet1").Copy
With ActiveSheet.UsedRange
.Value = .Value
End With
ActiveWorkbook.SaveAs filePath & counter & ".xlsx", FileFormat:=51
counter = counter + 1
Next ws
End Sub
This is mostly taken from here.
The counter is a bit of a hack to make sure that the files aren't all being saved as the same name and overwriting each other. Maybe there's a more appropriate way that you can get around this.

Loop to run macros from other workbooks

I would greatly appreciate your help with a macro that I am trying to create.
I have a pathway that looks as follows: K:\XXX\XXX\XXX\Module 1
Module 1 is a folder that contains a bunch of xlsm files named with a number (i.e. 100.xlsm, 110.xlsm, and so forth)
I would like to create a loop that:
Runs the macro in workbook 100.xlsm;
Saves the 100.xlsm (NOT "save as") when the macro is done running;
Closes the saved xlsm, moves on to the next file (i.e.
110.xlsm), and repeats the same steps.
Before running the loop, I would like to create a statement that stores the names of those xlsm files.
The macro below may give you an idea of what I am after. There are indeed several errors.
Sub update()
Dim path As String path = "K:\XXX\XXX\XXX\Module 1"
Dim list() As Integer
List=(100, 110, 137, 140)
For Each n As Integer In list
Application.Run (path & "\" &n.xslm!refresh)
Save WORKBOOK
Close WORKBOOK
Next
End Sub
I think something like the code below will achieve what you are wanting to do.
Note that the code first opens the workbook whose macro you want to run.
You can then run the macro in that opened workbook from your original workbook with the Application.Run() command, e.g.
Application.Run("book1.xlsm!mymacro"), or
result = Application.Run("book1.xlsm!mymacro", "Hello", 20)
The second example calls a macro that requires a string paramater and an integer parameter.
The fuller example below opens some specific workbooks called 100.xlsm, 110.xlsm, etc and then runs a macro in each of them called SayHelloMessage.
I hope this helps.
Sub RunMacrosInOtherWorkbooks()
Dim wbpath As String 'path where the workbooks containing the macros you want to run are saved
Dim wbnames() As String 'array containing names of workbooks whose macros you want to run
Dim wbTarget As Workbook 'current workbook who macro is being run
Dim macroname As String 'name of macro being run
wbpath = "C:\Test"
wbnames() = Split("100.xlsm,110.xlsm,137.xlsm,140.xlsm", ",") 'Just one way of creating the list of workbooks.
macroname = "SayHelloMessage"
Dim i As Integer
Dim result As Variant
For i = 0 To UBound(wbnames)
Set wbTarget = Workbooks.Open(wbpath & "\" & wbnames(i))
result = Application.Run(wbTarget.Name & "!" & macroname)
' result = Application.Run(wbTarget.Name & "!" & macroname, 76) 'calling a subroutine or function with an argument. You need something to catch a return code
wbTarget.Save
wbTarget.Close
Next
End Sub