Export Word header Bookmark to Excel UserForm1 Textbox - vba

I need VBA Code to get header bookmark in the Excel UserForm1 Textbox. Please assist me. I have got the page count, but not able to get this. I have placed the Code below, which I've tried, but it is not working.
I get error at:
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
and
wst.txtstatementof.Text = "MyBookmark"
Thanks in advance.
Sub ExportBookmarksToExcel()
Dim bk As Bookmark
Dim appXl As Excel.Application
Dim wbk As Excel.Workbook
Dim wst As Excel.Worksheet
Dim x As UserForm1
Set appXl = CreateObject("Excel.Application")
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
With appXl
.Visible = True
Set wbk = .Workbooks.Add
Set wst = wbk.UserForm1
wst.txtstatementof.Text = "MyBookmark"
End With
'For each bk In ActiveDocument.Bookmarks
'lRow = lRow + 1
' wst.x.UserForm1.txtstatementof.Text = bk.Name
'wst.Cells(lRow, 2) = bk.Range.Text
'Next bk
'wst.UsedRange.Columns.AutoFit
End Sub

Actually, you weren't far from success. Of course, this must fail:-
Set appXl = CreateObject("Excel.Application")
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
You can see that your Excel application is called appXl. Therefore it can't respond to ObjExcel.Workbooks.Open.
Below is the code that works.
Sub ExportBookmarksToExcel()
' MS Word variables:
Dim Bk As Bookmark
Dim R As Long
' MS Excel variables:
Dim appXl As Excel.Application
Dim Wbk As Excel.Workbook
Dim Wst As Excel.Worksheet
Set appXl = CreateObject("Excel.Application")
With appXl
.Visible = True
' Set Wbk = .Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
Set Wbk = .Workbooks.Add
Set Wst = Wbk.Worksheets(1)
' Wst.txtstatementof.Text = "MyBookmark" ' what is "txtstatementof" ?
End With
R = 2 ' keep Row 1 for captions
For Each Bk In ActiveDocument.Bookmarks
Wst.Cells(R, 1) = Bk.Name
Wst.Cells(R, 2) = Bk.Range.Text
R = R + 1
Next Bk
Wst.UsedRange.Columns.AutoFit
End Sub

Related

Issues Preserving Format from Word to Excel

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!

Export queries from Access-Form to Excel with Loop in VBA

I want to Export large data stock from Access to Excel. I'm doing that with a form.
My code with "DoCmd.TransferSpreadsheet acExport..." works normally, but the program breaks off because of the large data stock.
Perhaps with queries I can solve this Problem, or what do you think?
I am thankful for each tip! =)
you can you use below code: this will copy the datesheet view in your form and copy paste it in to one excel file .For this you just drag one sub form control from tool box in to your form and set the property of this sub form's source data as your query name and replace the sub form name in the code
Private Sub Command48_Click()
On Error GoTo Command13_Click_Err
Me.subformName.SetFocus
'DoCmd.GoToControl "Policy Ref"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
Dim xlapp As Excel.Application
Set xlapp = CreateObject("Excel.Application")
With xlapp
.Workbooks.Add
.ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
.Cells.Select
.Cells.EntireColumn.AutoFit
.Visible = True
.Range("a1").Select
End With
Command13_Click_Exit:
Exit Sub
Command13_Click_Err:
MsgBox Error$
Resume Command13_Click_Exit
End sub
'=======================
you can you use below code: this will copy the datesheet view in your form and copy paste it in to one excel file .For this you just drag one sub form control from tool box in to your form and set the property of this sub form's source data as your query name and replace the sub form name in the code
Private Sub Command48_Click()
On Error GoTo Command13_Click_Err
Me.subformName.SetFocus
'DoCmd.GoToControl "Policy Ref"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
Dim xlapp As Excel.Application
Set xlapp = CreateObject("Excel.Application")
With xlapp
.Workbooks.Add
.ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
.Cells.Select
.Cells.EntireColumn.AutoFit
.Visible = True
.Range("a1").Select
End With
Command13_Click_Exit:
Exit Sub
Command13_Click_Err:
MsgBox Error$
Resume Command13_Click_Exit
End sub
'''PPT
Sub pptExoprort()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationAutomatic
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim slideNum As Integer
Dim chartName As String
Dim tableName As String
Dim PPTCount As Integer
Dim PPSlideCount As Long
Dim oPPTShape As PowerPoint.Shape
Dim ShpNm As String
Dim ShtNm As String
Dim NewSlide As String
Dim myChart As PowerPoint.Chart
Dim wb As Workbook
Dim rngOp As Range
Dim ro As Range
Dim p As Integer
Dim v, v1, v2, v3, Vtot, VcaGr
Dim ws As Worksheet
Dim ch
Dim w As Worksheet
Dim x, pArr
Dim rN As String
Dim rt As String
Dim ax
Dim yTbN As String
'Call InitializeGlobal
''start year offset
prodSel = shtSet.Range("rSelProd")
x = shtSet.Range("rngMap").Value
pArr = fretPrVal(x, prodSel)
TY = 11 'number of years in chart
ThisWorkbook.Activate
Set w = ActiveSheet
Set PPApp = GetObject("", "Powerpoint.Application") '******************
PPTCount = PPApp.Presentations.Count
If PPTCount = 0 Then
MsgBox ("Please open a PPT to export the Charts!")
Exit Sub
End If
Set PPPres = PPApp.ActivePresentation '******************
For j = 0 To UBound(pArr)
If j = 0 Then
rN = "janport"
slideNum = 3
yTbN = "runport"
Else
rN = "janprod" & j
slideNum = 3 + j
yTbN = "runprod" & j
End If
chartName = "chtSalesPort"
Set PPSlide = PPPres.Slides(slideNum) '**************
PPApp.ActiveWindow.View.GotoSlide PPSlide.SlideIndex
Set myChart = PPSlide.Shapes(chartName).Chart '******************
myChart.ChartData.Activate '********************
Set wb = myChart.ChartData.Workbook '***********
Set ws = wb.Worksheets(1) '**************
Set rngOp = w.Range(rN).Offset(0, 1).Resize(12, 6)
Set ro = rngOp
' v1 = ro.Offset(1, 22).Resize(Lc, 1)
'ws.ListObjects("Table1").Resize Range("$A$1:$B$" & Ty + 1)
'ws.ListObjects("Table1").Resize Range("$A$1:$" & Chr(Lc + 1 + 64) & "$" & Ty + 1)
ws.Range("B2:g13").ClearContents '***********
rngOp.Copy '**********
ws.Range("B2:g13").PasteSpecial xlPasteValues '******************
End Sub
Sub Picture62_Click()
Dim charNamel As String
Dim leftm As Integer
Dim toptm As Integer
charNamel = "Chart 1"
leftm = 35
toptm = 180
Call chartposition(leftm, toptm, charNamel)
End Sub
Sub chartposition(leftm, toptm, charNamel)
ActiveSheet.ChartObjects(charNamel).Activate
'First we declare the variables we will be using
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim cht As Excel.ChartObject
Dim activslidenumber As Integer
'Look for existing instance
On Error Resume Next
Set newPowerPoint = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Let's create a new PowerPoint
If newPowerPoint Is Nothing Then
Set newPowerPoint = New PowerPoint.Application
End If
'Make a presentation in PowerPoint
' If newPowerPoint.Presentations.Count = 0 Then
' newPowerPoint.Presentations.Add
' End If
'Show the PowerPoint
newPowerPoint.Visible = True
On Error GoTo endd:
activslidenumber = Str(GetActiveSlide(newPowerPoint.ActiveWindow).SlideIndex)
Set activeSlide = newPowerPoint.ActivePresentation.Slides(activslidenumber)
ActiveChart.ChartArea.Copy
On Error GoTo endddd:
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteDefault).Select
'activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
'activeSlide.Shapes.PasteSpecial(DataType:=ppPasteOLEObject, DisplayAsIcon:=msoFalse).Select
endddd:
newPowerPoint.ActiveWindow.Selection.ShapeRange.Left = leftm
newPowerPoint.ActiveWindow.Selection.ShapeRange.Top = toptm
GoTo enddddd:
endd:
MsgBox ("Please keep your PPT file opened")
enddddd:
End Sub

Can't delete sheet

I'm trying to open a workbook and delete a sheet from it, but it runs the code without errors, and the sheet is still there...
I'm able to modify it, as I changed formulas to values on another sheet.
First of all - Yes, I know the "i" variable is set to do 1 iteration.
Somehow, now when I open the workbook it says it's locked by me - which I don't even know how to do.
So...how can I unlock it? When I go to File-->Info-->Permissions it says 'Anyone can copy, change and modify any part of this workbook.... I can delete the sheet manually as well...
Here's the code:
Sub Change()
Dim wb As Excel.Workbook
Set wb = ThisWorkbook
Dim ws As Excel.Worksheet
Set ws = wb.Sheets("FileSearch Results")
Dim rng As Range
Set rng = ws.UsedRange
Dim cPaths As Integer
cPaths = rng.Column
Dim i As Integer
i = rng.Row
Dim oExcel As Excel.Application
Set oExcel = New Excel.Application
Dim oWB As Workbook
Dim komm As Excel.Worksheet
Dim sh1 As Excel.Worksheet
Do While i < 2
Dim pth As String
pth = ws.Cells(i, cPaths)
Set oWB = oExcel.Workbooks.Open(pth)
Set sh1 = oWB.Worksheets("Sheet1")
With sh1.UsedRange
.Value = .Value
End With
Set komm = oWB.Worksheets("Kommentar")
Application.DisplayAlerts = False
komm.Delete
Application.DisplayAlerts = True
oWB.Close savechanges:=True
i = i + 1
Loop
End Sub
Any ideas?
Sub Change()
Dim wb As Excel.Workbook
Set wb = ActiveWorkbook 'ThisWorkbook
Dim ws As Excel.Worksheet
Set ws = wb.Sheets("FileSearch Results")
Dim rng As Range
Set rng = ws.UsedRange
Dim cPaths As Integer
cPaths = rng.Column
Dim i As Integer
i = rng.row
'Dim oExcel As Excel.Application ***CHANGED***
'Set oExcel = New Excel.Application ***CHANGED***
'Dim oWB As Workbook ***CHANGED***
Dim komm As Excel.Worksheet
Dim sh1 As Excel.Worksheet
Do While i < 2
Dim pth As String
pth = ws.Cells(i, cPaths)
'Set oWB = oExcel.Workbooks.Open(pth) ***CHANGED***
Workbooks.Open (pth) '***ADDED***
Set sh1 = ActiveWorkbook.Worksheets("Sheet1") 'oWB.Worksheets("Sheet1") ***CHANGED***
With sh1.UsedRange
.Value = .Value
End With
Set komm = ActiveWorkbook.Worksheets("Kommentar") 'oWB.Worksheets("Kommentar") ***CHANGED***
Application.DisplayAlerts = False
komm.Delete
Application.DisplayAlerts = True
ActiveWorkbook.Close savechanges:=True 'oWB.Close savechanges:=True ***CHANGED***
i = i + 1
Loop
End Sub
This now opens the workbook and deletes the sheet in the foreground rather than invoking a new instance of Excel and deleting the sheet in the background. This is why the file stays locked, as the new instance which isn't closed by the code, still holds it.
For anyone running into this in the future (like myself), the actual problem is with the mix up in scope when calling Application.DisplayAlerts.
komm is a sheet in oWB, which exists in the new instance of excel oExcel.
Application is a completely different instance and therefor has no effect.
Since the code isn't actually disabling the prompt in the correct instance of excel (oExcel) and it is presumably not visible, the code will just ignore the command and move on.
The simple fix is to use oExcel instead of Application:
Set komm = oWB.Worksheets("Kommentar")
oExcel.DisplayAlerts = False
komm.Delete
oExcel.DisplayAlerts = True

How to manipulate an excel workbook with Excel.Workbook

So, I can't find any methods with file opening in Excel.Workbook or Excel.Application, and I am wondering why.
I have path to an Excel file, and I would like to manipulate it. I understand I have to use Excel.Application, Excel.Workbook, and Excel.Worksheet. The file to the Excel file is ExcelFilePath, what should I do to make it possible?
You first need to add the reference to Microsoft.Office.Interop.Excel to your project in order to use the Excel API, then fill the variables:
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWS As Excel.Worksheet
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open(sFilePath)
xlWS = CType(xlWorkBook.Worksheets(sheetNameOrIndex), Excel.Worksheet)
And then you only need to use the methods they have. For example:
Dim sVar as String = xlWS.Range("C5").Value.ToString()
Try this: from my project
Dim xapp As New Microsoft.Office.Interop.Excel.Application
Dim wb As Workbook = xapp.Workbooks.Add
Dim ws As Worksheet = wb.Worksheets(1)
ws.Activate()
'Fill header of the sheet----------------------------------
For i As Integer = 1 To dgvcustomer.Columns.Count
ws.Cells(1, i) = dgvcustomer.Columns(i - 1).HeaderText
Next
'End header------------------------------------------------
Dim Dgrow, Dgcell, Dgcol As Integer
Dgrow = 1
Dgcell = 1
'Fill Sheet ------------------------------------------------------------------------------------------------
While (Dgrow <= dgvcustomer.Rows.Count)
Dgcol = 1
While (Dgcol <= ws.UsedRange.Columns().Count)
ws.Cells(Dgrow + 1, Dgcol).value = dgvcustomer.Rows(Dgrow - 1).Cells(ws.Cells(1, Dgcol).value).Value
Dgcol += 1
End While
Dgrow += 1
End While
'End fill sheet---------------------------------------------------------------------------------------------
wb.SaveAs(dlgSaveFile.FileName)
wb.Close()
xapp.Quit()

How to format a closed Excel sheet using VBA

I have sheet1.xls which is closed. I am working in sheet2.xls VBA as follows.
With Range("A:XFD")
<I need Some Code here to format entire sheet1.xls cells into string format>
End With
Kinldy help.Thanks
Something like this will allow you to format the closed book. It is opened and then formatted and then closed again.
Option Explicit
Public Sub Format_Closed_Sheet()
Dim sht1book As Workbook
Dim sht1ws As Worksheet
Dim strValue As String
Dim rng As Range
Application.ScreenUpdating = False
With Application
'--> Open sheet1.xls
Set sht1book = .Workbooks.Open _
("Path to Sheet1.xls")
End With
Set sht1ws = sht1book.Sheets("Sheet1")
'--> Format the range as text
Set rng = sht1ws.Range("A:XFD")
rng.NumberFormat = "#"
'--> Save sheet1.xls and close
Application.DisplayAlerts = False
sht1book.Save
sht1book.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This is how I would do it:
Dim b As Workbook
Dim sh As Worksheet
Set b = Workbooks.Open("C:\mypath\mybook.xls") ' or wherever your workbook is
Set sh = b.Sheets("Sheet1") ' or whatever sheet
sh.Cells.NumberFormat = "#" ' format as Text
b.Close
If you want to format all of the sheets in your workbook as text, you can do this:
For Each sh In wb.Sheets
sh.Cells.NumberFormat = "#" ' format as Text
Next sh
Just declare a workbook and sheet:
dim oBook as excel.workbook
dim oSheet as excel.worksheet
set oBook = workbooks.open("<workbook path and filename>")
set oSheet = oBook.sheets("<SheetName>")
then:
with oSheet.range("A:XFD")
<Format>
end with
oBook.close
set oBook = nothing
set oSheet = nothing
And so on.