Vba excel пространство имен

Содержание

  • 1 Accessing Default Folders within the NameSpace Object
  • 2 Accessing Other Folders within the NameSpace Object
  • 3 Creating a New Folder
  • 4 Deleting a Folder
  • 5 olFolderContacts
  • 6 olFolderDeletedItems,
  • 7 olFolderDrafts,
  • 8 olFolderInbox,
  • 9 olFolderJournal,
  • 10 olFolderNotes,
  • 11 olFolderOutbox,
  • 12 olFolderSentMail,
  • 13 olFolderTasks,
  • 14 olPublicFoldersAllPublicFolders.
  • 15 Returns the NameSpace and uses the CurrentUser property to display the name of the current user in a message box:
  • 16 Understanding General Methods for Working with Outlook Objects
  • 17 Using the NewMail Event and NewMailEx Event

Accessing Default Folders within the NameSpace Object

   <source lang="vb">

«olFolderCalendar,
Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderCalendar)

End Sub

</source>
   
  

Accessing Other Folders within the NameSpace Object

   <source lang="vb">

«A list of all the folders contained in the namespace:
Sub List_All_NameSpace_Folders()

   Dim myNS As NameSpace
   Dim myFolder As MAPIFolder
   Dim mySubfolder As MAPIFolder
   strFolderList = "Your Outlook NameSpace contains these folders:" 
   Set myNS = Application.GetNamespace("MAPI")
   With myNS
       For Each myFolder In myNS.Folders
           strFolderList = strFolderList & myFolder.Name & vbCr
           For Each mySubfolder In myFolder.Folders
               Debug.Print mySubfolder.Name 
           Next mySubfolder
       Next myFolder
   End With

End Sub

</source>
   
  

Creating a New Folder

   <source lang="vb">

Sub newFolder()

   Application.GetNamespace("MAPI").GetDefaultFolder(olFolderTasks) _
       .Folders.Add Name:="Personal Tasks", Type:=olFolderTasks

End Sub

</source>
   
  

Deleting a Folder

   <source lang="vb">

Sub delete()

   Application.GetNamespace("MAPI").GetDefaultFolder(olFolderTasks) _
       .Folders("Personal Tasks").Delete

End Sub

</source>
   
  

olFolderContacts

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderContacts)

End Sub

</source>
   
  

olFolderDeletedItems,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderDeletedItems)

End Sub

</source>
   
  

olFolderDrafts,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderDrafts)

End Sub

</source>
   
  

olFolderInbox,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderInbox)

End Sub

</source>
   
  

olFolderJournal,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderJournal)

End Sub

</source>
   
  

olFolderNotes,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderNotes)

End Sub

</source>
   
  

olFolderOutbox,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderOutbox)

End Sub

</source>
   
  

olFolderSentMail,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderSentMail)

End Sub

</source>
   
  

olFolderTasks,

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olFolderTasks)

End Sub

</source>
   
  

olPublicFoldersAllPublicFolders.

   <source lang="vb">

Sub folder()

   Dim myCal As MAPIFolder
   Set myCal = Application.GetNamespace("MAPI") _
       .GetDefaultFolder(FolderType:=olPublicFoldersAllPublicFolders)

End Sub

</source>
   
  

Returns the NameSpace and uses the CurrentUser property to display the name of the current user in a message box:

   <source lang="vb">

Sub current()

   MsgBox Application.GetNamespace("MAPI").CurrentUser

End Sub

</source>
   
  

Understanding General Methods for Working with Outlook Objects

   <source lang="vb">

Sub display()

   Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Display

End Sub

</source>
   
  

Using the NewMail Event and NewMailEx Event

   <source lang="vb">

Sub Application_NewMail()

   If MsgBox("You have new mail. Do you want to see your Inbox?", _
       vbYesNo + vbInformation, "New Mail Alert") = vbYes Then
       Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Display
   End If

End Sub

</source>

So…another xml namespace question. I want to write this namespace with vba

<?xml version="1.0" encoding="utf-8"?>
<Datas xsi:schemaLocation="uri:rhubarb:pie RHUBARB%20PIE%202012.xsd" xmlns="uri:rhubarb:pie" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Datas>

and here is my code so far

Option Explicit

Public Sub Create_Database()

'Declare document objects
Dim xDoc As MSXML2.DOMDocument60
Dim xNode As IXMLDOMNode
Dim xRoot As IXMLDOMElement

'create new DOMDocument
Set xDoc = New DOMDocument60

'Create processing instructions
Set xNode = xDoc.createProcessingInstruction("xml", "version='1.0' encoding= 'UTF-8'")
Set xNode = xDoc.InsertBefore(xNode, xDoc.ChildNodes.Item(0))

'create root element
Set xRoot = xDoc.createElement("Datas")
xDoc.appendChild xRoot
xDoc.DocumentElement.setAttribute "xsi:schemaLocation", "uri:rhubarb:pie RHUBARB%20PIE%202012.xsd"
xDoc.DocumentElement.setAttribute "xmlns", "uri:rhubarb:pie"
xDoc.DocumentElement.setAttribute "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"

'save xml file
xDoc.Save "C:UsersdannyDesktopxmlDatabase.xml"
'clear xDoc from memory
Set xDoc = Nothing
End Sub

…but I know in writing the namespace I have too many arguments. The only thing I can find online would be to write my namespace like this:

xDoc.DocumentElement.setAttribute "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"

I keep getting an error about too many arguments. My question: How do I write a more complex namespace? Or is that even a correct way to go about writing it?

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

XmlNamespace object (Excel)

vbaxl10.chm743072

vbaxl10.chm743072

excel

Excel.XmlNamespace

4c39c739-b848-5fec-c354-9fa56daf1d5d

04/03/2019

medium

XmlNamespace object (Excel)

Represents a namespace that has been added to a workbook.

Remarks

Use the Prefix property to return the prefix of an XmlNamespace object.

Use the Uri property to return the Uniform Resource Identifier (URI) of an XmlNamespace object.

Properties

  • Application
  • Creator
  • Parent
  • Prefix
  • Uri

See also

  • Excel Object Model Reference

[!includeSupport and feedback]

Интересный вопрос (постоянно используя их, но не думал о их точном значении). Определение оператора Imports (то же самое для using) довольно ясно: его единственная функция сокращает ссылки, удаляя соответствующие пространства имен. Таким образом, первый вопрос, задаваемый вопросом: имеет ли вообще VBA такую ​​вещь (пространства имен)? И ответ — нет, поскольку вы можете читать из нескольких источников; Примеры: Ссылка 1 Ссылка 2

Итак, после того, как не было найдено ни одной ссылки на любой оператор VBA, делающий что-то похожее на Imports / using и подтвердив, что VBA не рассматривает «структуру», оправдывающую их использование (пространства имен), я думаю, что я могу сказать: нет, в VBA такого не происходит.

Кроме того, вы должны иметь в виду, что у него не было бы реальной применимости. Например: при преобразовании кода VB.NET, где Imports может использоваться, например:

Imports Microsoft.Office.Interop.Word
...
Dim wdApp As Application

, код будет полностью изменен, так что результирующая строка не будет длинной:

Dim wdApp As Word.Application ' Prefacing the library's display name.

Я думаю, что это хорошая графическая причина, объясняющая, почему VBA не нуждается в таких вещах: VB.NET учитывает самые разные реалии, которые должны быть должным образом классифицированы (пространства имен); VBA учитывает гораздо меньшее количество ситуаций и, следовательно, может позволить себе не выполнять столь систематическую, давно названную классификацию.

—————— ——— CLARIFICATION

Imports / using — простое сокращение имени, то есть вместо того, чтобы писать any.whatever2.whatever3 каждый раз, когда вы используете объект данного пространства имен в Module / Class вы добавляете в начале инструкцию Imports / using, которая в основном означает: «для всех членов пространства имен X просто забудьте обо всех заголовках bla, bla» ,

Я не говорю, что вы не можете эмулировать такое поведение; просто подчеркивая, что наличие встроенных функций для коротких имен имеет смысл в VB.NET, где имена могут стать очень длинными, но не так много в VBA.

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

adding namespaces

adding namespaces

(OP)

10 Mar 08 08:04

Hello all,

In Excel 2003 I want to copy the contents of XML files. I open the original and copy the content to a new xml file. Also I can change the number of a certain element, the first one under the root element. My xml files contain namespaces.

This is done with help of XPath. But to use this I have to add the namespaces (XMLDoc.setProperty «SelectionNamespaces», strNs. strNS is a variable that contains the namespaces).

When I run the script for the first time, everything works. But the second time I get error number -2147467259 and the text says «Duplicate attribute».

What causes this and how do I resolve it?

If my description is not clear please ask.

Thanks in advance,
Sjakie.

———————————————
Yes, the world is full of strange people.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Понравилась статья? Поделить с друзьями:
  • Vba excel пропуск ошибок
  • Vba excel прокрутка листа
  • Vba excel пройти по всем строкам в листе
  • Vba excel продолжить for if
  • Vba excel программирование уроки