I have the below code to get all the Sheetnames of a selected workbook. How do I get all the names of the sheets and import them into a table in the Access Database?
Public Sub PickSheets1(fileName As String)
Dim objExc As Object
Dim objWbk As Object
Dim objWsh As Object
SQLInsert = "INSERT INTO Sheets Table (Sheets) Values (objWbk.Worksheets.Name)"
Set TabInsert = CurrentDb.CreateTableDef("Sheets Table")
Set TabFields = TabInsert.CreateField("Sheets")
Set objExc = CreateObject("Excel.Application")
Set objWbk = objExc.Workbooks.Open(fileName)
Set objWsh = objWbk.Worksheets.Name
DoCmd.RunSQL SQLInsert
'For Each objWsh In objWbk.Worksheets
'TabFields("Sheets").Value objWsh.Name
Set objWsh = Nothing
objWbk.Close
Set objWbk = Nothing
objExc.Quit
Set objExc = Nothing
End Sub
So from within MSAccess you can run this code. Its uses DAO to add the sheet name to the table. Assumes that the table 'Sheets Table' with column 'SheetName' already exists.
call loadSheetNames("C:Path\Workbook.xlsx")
Function loadSheetNames(pstrWB As String)
' Access
Dim db As DAO.Database
Dim rst As DAO.Recordset
' Excel
Dim xl As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Set db = CurrentDb
Set rst = db.OpenRecordset("Sheets Table")
Set xl = CreateObject("Excel.Application")
Set xlWB = xl.Workbooks.Open(pstrWB)
For Each xlWS In xlWB.Sheets
Debug.Print xlWS.NAME
rst.AddNew
rst("SheetName") = xlWS.NAME
rst.update
Next
Set rst = Nothing
Set db = Nothing
Set xlWS = Nothing
Set xlWB = Nothing
Set xl = Nothing
End Function
If you want to run the code from within Excel, I can give you that as well.
Related
I'm struggling trying to export a Word table to an Excel sheet, while preserving the number formatting. My code works as shown below, but the part I commented out is how I'm currently trying to do it (and failing). Could someone point out what I'm doing wrong?
Public Sub CopyTableToExcel()
Dim xlApp As Excel.Application
Dim xlwb As Excel.Workbook
Dim doc As Word.Document
Dim tbl As Word.Table
Dim lastRow As Long, lastColumn As Integer
Dim tblRange As Word.Range
Dim excelRange As Excel.Range
Set doc = ThisDocument
Set xlApp = CreateObject("Excel.Application")
Set xlwb = xlApp.Workbooks.Add 'Create new workbook
Set tbl = doc.Tables(2)
With tbl:
lastRow = .Rows.Count
lastColumn = .Columns.Count
Set tblRange = .Cell(1, 1).Range
tblRange.End = .Cell(lastRow, lastColumn).Range.End
tblRange.Copy
xlwb.Worksheets(1).Paste
'This part doesn't work, but I'm trying to do something like this:
'Set excelRange = xlwb.Worksheets("Sheet1").Range("A1")
'excelRange.PasteSpecial (xlPasteValuesAndNumberFormats)
End With
Set xlwb = Nothing
Set xlApp = Nothing
Set tbl = Nothing
Set doc = Nothing
End Sub
Thanks for your help!
New to Outlook VBA what are my choices if I want Outlook to look into an Excel file's A column for a value and return the B column value? (Same as a VLOOKUP)
Option Explicit
Sub LookUpExcel()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim ExcelFileName As String
Dim ColumnA As String
Dim ColumnB As String
Dim oMsg As MailItem
ExcelFileName = "C:\Users\vfdme\Desktop\test.xlsx"
Set exWb = objExcel.Workbooks.Open(ExcelFileName)
ColumnA = InputBox("Please Column A value.")
'[VLOOKUP / Search function?]
MsgBox (ColumnB)
ExitRoutine:
Set oMsg = Nothing
Set exWb = Nothing
Set objExcel = Nothing
End Sub
Got the code to work properly :)
Thanks #braX for the tip.
Sub LookUpExcel()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim ExcelFileName As String
Dim ColumnA As String
Dim ColumnB As String
Dim oMsg As MailItem
ExcelFileName = "C:\Filelocation\Testfile.xlsx"
Set exWb = objExcel.Workbooks.Add(ExcelFileName)
ColumnA = InputBox("Please Column A value.")
ColumnB = exWb.Worksheets("Sheet1").Range("A:A").Find(ColumnA).Offset(0, 1).Value
msgbox (ColumnB)
ExitRoutine:
Set oMsg = Nothing
Set exWb = Nothing
Set objExcel = Nothing
End Sub
I am creating a macro in outlook to send an eamil with some specific information in it. But only some people from the list in an excel sheet can send that email out. When they hit "SEND" on that macro, it needs to open the excel sheet and varify if that person is listed on the list. If he isn't it should just give him an error " You are not eligible to send this message" .
I am able to open the excel file using the code below. But I am not sure how to do the checking (names are listed on Sheet1 from C1: C100) to see that sending person is listed in there.
Below is my code:
[Dim strFldr As String
Dim OutMail As Object
Dim xlApp As Object
strFldr = "C:\\users-d\gxg063\Gift\test\"
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Visible = True
xlApp.Workbooks.Open strFldr & "\RegionalAuthority.xlsx"]
Let me know how this works out - you'll need a reference to Excel in your Outloook VBE
Sub TestSub()
Dim strFldr As String
Dim OutMail As Object
Dim xlApp As Excel.Application
Dim xlWb As Workbook
Dim xlWs As Worksheet
Dim r As Range
Dim User As String
Dim c As Range
strFldr = "C:\\users-d\gxg063\Gift\test\"
Set xlApp = New Excel.Application
Set xlWb = xlApp.Workbooks.Open(strFldr & "\RegionalAuthority.xlsx")
Set xlWs = xlWb.Worksheets("Sheet1")
Set r = xlWs.Range("C1:C100")
User = (Environ$("Username"))
For Each c In r
If c = User Then
'Call your Send Macro here
Exit For
End If
Next c
xlApp.Visible = True
Set xlApp = Nothing
Set xlWb = Nothing
Set xlWs = Nothing
End Sub
I'm a bit of newbie when it comes to these things, so apologies if this is a stupid question.
I need to run an SQL query from a piece of VBA. The query is a little odd, because it contains a VBA variable in its function. Otherwise everything is pretty straight forward. The VBA should call the query and then insert it into a client excel document.
Every time I run the query within Access everything is fine, the function returns the correct value and filters down the columns. Every time I run it from VBA in Excel it says "Run-Time Error "3085": Undefined Function 'CutOff' in expression.
I've look for info and have found old sites saying that Access 2003 sometimes has an issue doing this sort of thing, but I'm running 2010 (I think). Just hoping the problem is solve-able and greatly appreciate any advice.
The query is as follows :
SELECT [<TableName>].ID...*
FROM [<TableName>]
WHERE ((([<TableName>].ID)>CutOff()))
ORDER BY [<TableName>]].ID;
Public Function Cutoff()
Dim WB1 As Excel.Workbook, WS1 As Excel.Worksheet
Dim y As Long
Set WB1 = Workbooks.Open("C:\filepath.z.xlsm")
Set WS1 = WB1.Sheets("Sheet2")
y = WS1.Range("A1").End(xlDown).Offset(0, 0).Value
'Debug.Print y
Cutoff = y
'Debug.Print Cutoff
End Function
The VBA that runs it is operated from Excel. I have tried the following:
Sub Export2()
Dim db2 As Database
Dim rs2 As DAO.Recordset, i As Long, sFormat As String
Dim WB2 As Excel.Workbook, WS2 As Excel.Worksheet
Set WB2 = Workbooks.Open("C:\FilePath.z.xlsm")
Set WS2 = WB.Sheets("Sheet2")
Set db2 = OpenDatabase("C:\FilePath.x.mdb")
Set qd2 = db2.QueryDefs("ExportCount")
Set rs2 = qd2.OpenRecordset()
If rs2.EOF Then
GoTo EndLoop
End If
WS2.Range("a1").End(xlsDown).Offset(1, 0).CopyFromRecordset rs2
WS2.Cells.EntireColumn.AutoFit: WS2.Cells.EntireRow.AutoFit
EndLoop:
Set WB = Nothing
Set WS2 = Nothing
Set db2 = Nothing
Set qd2 = Nothing
Set rs2 = Nothing
End Sub
EDIT:
Have also tried:
Sub SQLquery1()
Dim WB1 As Excel.Workbook, WS1 As Excel.Worksheet
Dim wt As DAO.Database
Dim we As DAO.Recordset
Dim wd As DAO.QueryDef
Set WB1 = Workbooks.Open("C:\x.xlsm")
Set WS1 = WB1.Sheets("Sheet2")
mySQLVariable = WS1.Range("A1").End(xlDown).Offset(0, 0).Value
'Debug.Print mySQLVariable
Set wt = OpenDatabase("C:\z.mdb")
Set wd = wt.QueryDefs("ExportCount")
Set we = wd.OpenRecordset("h")
WS2.Range("a1").End(xlsDown).Offset(1, 0).CopyFromRecordset wd
WS2.Cells.EntireColumn.AutoFit: WS2.Cells.EntireRow.AutoFit
Set WB1 = Nothing
Set WS1 = Nothing
Set wt = Nothing
Set we = Nothing
Set wd = Nothing
End Sub
EDIT2
Sub CreateQueryDef()
Dim WB1 As Excel.Workbook, WS1 As Excel.Worksheet
Dim dbPP As Database
Dim qdfTemp As QueryDef
Dim Counter As DAO.Recordset
Dim mySQLVariable As String
Dim rs5 As DAO.Recordset
Set dbPP = OpenDatabase("C:\filepath\z.mdb")
Set Counter = dbPP.OpenRecordset("j")
Set WB1 = Workbooks.Open("C:\filepath\x.xlsm")
Set WS1 = WB1.Sheets("Sheet2")
mySQLVariable = WS1.Range("A1").End(xlDown).Offset(0, 0).Value
'Debug.Print mySQLVariable
With dbPP
Set qdfTemp = dbPP.CreateQueryDef("NewQueryDef", "SELECT * FROM [j]")
'WHERE ((j.[ID])=>(mySQLVariable)))") I can't get the syntax of these lines right - they are supposed to all be on the same line
Set rs5 = qdfTemp.OpenRecordset() ' maybe Set rs5 = qdfTemp.OpenRecordset("NewQueryDef")?
End With
WS1.Range("a1").End(xlsDown).Offset(1, 0).CopyFromRecordset rs5
WS1.Cells.EntireColumn.AutoFit: WS2.Cells.EntireRow.AutoFit
dbPP.QueryDefs.Delete "NewQueryDef"
End Sub
Or
Sub CreateQueryDef()
Dim dbPP As Database
Dim qdfTemp As QueryDef
Dim Counter As DAO.Recordset
Dim mySQLVariable As String
Dim rs5 As DAO.Recordset
Set dbPP = OpenDatabase("C:\filepath\z.mdb")
Set Counter = dbPP.OpenRecordset("j")
mySQLVariable = CutOff
'Debug.Print mySQLVariable
With dbPP
Set qdfTemp = dbPP.CreateQueryDef("NewQueryDef", "SELECT * FROM [j] WHERE ((j.[ID])=>(mySQLVariable)))")
Set rs5 = qdfTemp.OpenRecordset("NewQueryDef")
End With
WS1.Range("A1").End(xlsDown).Offset(1, 0).CopyFromRecordset rs5
WS1.Cells.EntireColumn.AutoFit: WS2.Cells.EntireRow.AutoFit
dbPP.QueryDefs.Delete "NewQueryDef"
dbPP.Close
Set dbPP = Nothing
Set qdfTemp = Nothing
Set Counter = Nothing
Set mySQLVariable = Nothing
Set rs5 = Nothing
End Sub
Public Function Cutoff()
Dim WB1 As Excel.Workbook, WS1 As Excel.Worksheet
Dim y As Long
Set WB1 = Workbooks.Open("C:\filepath.z.xlsm")
Set WS1 = WB1.Sheets("Sheet2")
y = WS1.Range("A1").End(xlDown).Offset(0, 0).Value
'Debug.Print y
Cutoff = y
'Debug.Print Cutoff
End Function
Worked out what I was doing wrong.
The current value of the variable needs to be inserted into an SQL string written in VBA and passed to Access as a temporary query. The value of the variable is fixed by the time it is handed to Access, so Access doesn't need to run a macro to retrieve it, which would require the database to be open with macros enabled e.g.:
Public y As String
Sub definey()
y = (VariableInput)
Call Query
End Sub
Sub Query
Dim q As DAO.Database
Dim s As DAO.Recordset
Dim mySQLVariable As String
Dim strSQL As String
mySQLVariable = y
strSQL = "SELECT * FROM [Table1] WHERE (((Table1.ID)>" & "Chr$36 MySQLVariable Chr$36"))
'I'm free writing, not copying from code, so apologies if this isn't quite right
Set q = OpenDatabase("Filepath\h.mdb")
Set s = q.OpenRecordset(strSQL)
'... then copy to workbook.
End Sub
I have the following code as part of my sub trying to assign a range:
'Set xlApp = CreateObject("Excel.Application")
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
xlApp.Visible = False
xlApp.ScreenUpdating = False
Dim CRsFile As String
Dim CRsMaxRow As Integer
' get the CR list
CRsFile = "CRs.xls"
Set CRsWB = xlApp.Workbooks.Open("C:\Docs\" + CRsFile)
With CRsWB.Worksheets("Sheet1")
.Activate
CRsMaxRow = .Range("A1").CurrentRegion.Rows.Count
Set CRs = .Range("A2:M" & CRsMaxRow)
End With
Dim interestingFiles As Range
' get the files names that we consider interesting to track
Set FilesWB = xlApp.Workbooks.Open("files.xlsx")
With FilesWB.Worksheets("files")
.Activate
Set interestingFiles = .Range("A2:E5")
End With
Do you have any idea why am I getting a run time type mismatch error?
If you run the code from Word then the problem is in the declaration of 'interestingFiles' variable. Range exist in Word as well so use either Variant or add reference to Excel and then use Excel.Range.
Without Excel reference:
Dim interestingFiles As Variant
And with Excel reference:
Dim interestingFiles As Excel.Range
Kindly set xlApp object as in below code.
Also you provide complete path for your workbook when opening it.
Sub test()
Dim interestingFiles As Range
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
' get the files names
Dim path As String
path = "C:\Users\Santosh\Desktop\file1.xlsx"
Set FilesWB = xlApp.Workbooks.Open(path)
With FilesWB.Worksheets(1)
.Activate
Set interestingFiles = .Range("A2:E5")
End With
End Sub