VBA: Selecting range by variables

I recorded a macro with ‘Relative References’ and this is what I got : Range(“F10”).Select ActiveCell.Offset(0, 3).Range(“A1:D11”).Select Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following: Dim MyRange as String MyRange = “A1:D11” Range(MyRange).Select And it … Read more

Run same excel macro on multiple excel files

Assuming that you put your files in “Files” directory relative to your master workbook your code might look like this: Sub ProcessFiles() Dim Filename, Pathname As String Dim wb As Workbook Pathname = ActiveWorkbook.Path & “\Files\” Filename = Dir(Pathname & “*.xls”) Do While Filename <> “” Set wb = Workbooks.Open(Pathname & Filename) DoWork wb wb.Close … Read more

Copy data from another Workbook through VBA

The best (and easiest) way to copy data from a workbook to another is to use the object model of Excel. Option Explicit Sub test() Dim wb As Workbook, wb2 As Workbook Dim ws As Worksheet Dim vFile As Variant ‘Set source workbook Set wb = ActiveWorkbook ‘Open the target workbook vFile = Application.GetOpenFilename(“Excel-files,*.xls”, _ … Read more

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this: Public wbA as Workbook Public wbB as Workbook Sub MySubRoutine() Set wbA = Workbooks.Open(“C:\file.xlsx”) Set wbB = Workbooks.Open(“C:\file2.xlsx”) OtherSubRoutine End Sub Sub OtherSubRoutine() MsgBox wbA.Name, vbInformation End Sub Alternately, you can pass variables between subroutines: Sub MySubRoutine() Dim wbA as Workbook Dim wbB as Workbook Set wbA = … Read more

Saving excel worksheet to CSV files with filename+worksheet name using VB [duplicate]

I think this is what you want… Sub SaveWorksheetsAsCsv() Dim WS As Excel.Worksheet Dim SaveToDirectory As String Dim CurrentWorkbook As String Dim CurrentFormat As Long CurrentWorkbook = ThisWorkbook.FullName CurrentFormat = ThisWorkbook.FileFormat ‘ Store current details for the workbook SaveToDirectory = “H:\test\” For Each WS In Application.ActiveWorkbook.Worksheets WS.SaveAs SaveToDirectory & WS.Name, xlCSV Next Application.DisplayAlerts = False … Read more